• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7 
8 #include "src/gpu/ganesh/vk/GrVkUniformHandler.h"
9 
10 #include "src/gpu/ganesh/GrTexture.h"
11 #include "src/gpu/ganesh/GrUtil.h"
12 #include "src/gpu/ganesh/glsl/GrGLSLProgramBuilder.h"
13 #include "src/gpu/ganesh/vk/GrVkGpu.h"
14 #include "src/gpu/ganesh/vk/GrVkPipelineStateBuilder.h"
15 #include "src/gpu/ganesh/vk/GrVkTexture.h"
16 
17 // To determine whether a current offset is aligned, we can just 'and' the lowest bits with the
18 // alignment mask. A value of 0 means aligned, any other value is how many bytes past alignment we
19 // are. This works since all alignments are powers of 2. The mask is always (alignment - 1).
20 // This alignment mask will give correct alignments for using the std430 block layout. If you want
21 // the std140 alignment, you can use this, but then make sure if you have an array type it is
22 // aligned to 16 bytes (i.e. has mask of 0xF).
23 // These are designated in the Vulkan spec, section 14.5.4 "Offset and Stride Assignment".
24 // https://www.khronos.org/registry/vulkan/specs/1.0-wsi_extensions/html/vkspec.html#interfaces-resources-layout
sksltype_to_alignment_mask(SkSLType type)25 static uint32_t sksltype_to_alignment_mask(SkSLType type) {
26     switch(type) {
27         case SkSLType::kShort: // fall through
28         case SkSLType::kUShort:
29             return 0x1;
30         case SkSLType::kShort2: // fall through
31         case SkSLType::kUShort2:
32             return 0x3;
33         case SkSLType::kShort3: // fall through
34         case SkSLType::kShort4:
35         case SkSLType::kUShort3:
36         case SkSLType::kUShort4:
37             return 0x7;
38         case SkSLType::kInt:
39         case SkSLType::kUInt:
40             return 0x3;
41         case SkSLType::kInt2:
42         case SkSLType::kUInt2:
43             return 0x7;
44         case SkSLType::kInt3:
45         case SkSLType::kUInt3:
46         case SkSLType::kInt4:
47         case SkSLType::kUInt4:
48             return 0xF;
49         case SkSLType::kHalf: // fall through
50         case SkSLType::kFloat:
51             return 0x3;
52         case SkSLType::kHalf2: // fall through
53         case SkSLType::kFloat2:
54             return 0x7;
55         case SkSLType::kHalf3: // fall through
56         case SkSLType::kFloat3:
57             return 0xF;
58         case SkSLType::kHalf4: // fall through
59         case SkSLType::kFloat4:
60             return 0xF;
61         case SkSLType::kHalf2x2: // fall through
62         case SkSLType::kFloat2x2:
63             return 0x7;
64         case SkSLType::kHalf3x3: // fall through
65         case SkSLType::kFloat3x3:
66             return 0xF;
67         case SkSLType::kHalf4x4: // fall through
68         case SkSLType::kFloat4x4:
69             return 0xF;
70 
71         // This query is only valid for certain types.
72         case SkSLType::kVoid:
73         case SkSLType::kBool:
74         case SkSLType::kBool2:
75         case SkSLType::kBool3:
76         case SkSLType::kBool4:
77         case SkSLType::kTexture2DSampler:
78         case SkSLType::kTextureExternalSampler:
79         case SkSLType::kTexture2DRectSampler:
80         case SkSLType::kSampler:
81         case SkSLType::kTexture2D:
82         case SkSLType::kInput:
83             break;
84     }
85     SK_ABORT("Unexpected type");
86 }
87 
88 /** Returns the size in bytes taken up in vulkanbuffers for SkSLTypes. */
sksltype_to_vk_size(SkSLType type,int layout)89 static inline uint32_t sksltype_to_vk_size(SkSLType type, int layout) {
90     switch(type) {
91         case SkSLType::kShort:
92             return sizeof(int16_t);
93         case SkSLType::kShort2:
94             return 2 * sizeof(int16_t);
95         case SkSLType::kShort3:
96             return 3 * sizeof(int16_t);
97         case SkSLType::kShort4:
98             return 4 * sizeof(int16_t);
99         case SkSLType::kUShort:
100             return sizeof(uint16_t);
101         case SkSLType::kUShort2:
102             return 2 * sizeof(uint16_t);
103         case SkSLType::kUShort3:
104             return 3 * sizeof(uint16_t);
105         case SkSLType::kUShort4:
106             return 4 * sizeof(uint16_t);
107         case SkSLType::kHalf: // fall through
108         case SkSLType::kFloat:
109             return sizeof(float);
110         case SkSLType::kHalf2: // fall through
111         case SkSLType::kFloat2:
112             return 2 * sizeof(float);
113         case SkSLType::kHalf3: // fall through
114         case SkSLType::kFloat3:
115             return 3 * sizeof(float);
116         case SkSLType::kHalf4: // fall through
117         case SkSLType::kFloat4:
118             return 4 * sizeof(float);
119         case SkSLType::kInt: // fall through
120         case SkSLType::kUInt:
121             return sizeof(int32_t);
122         case SkSLType::kInt2: // fall through
123         case SkSLType::kUInt2:
124             return 2 * sizeof(int32_t);
125         case SkSLType::kInt3: // fall through
126         case SkSLType::kUInt3:
127             return 3 * sizeof(int32_t);
128         case SkSLType::kInt4: // fall through
129         case SkSLType::kUInt4:
130             return 4 * sizeof(int32_t);
131         case SkSLType::kHalf2x2: // fall through
132         case SkSLType::kFloat2x2:
133             if (layout == GrVkUniformHandler::kStd430Layout) {
134                 return 4 * sizeof(float);
135             } else {
136                 return 8 * sizeof(float);
137             }
138         case SkSLType::kHalf3x3: // fall through
139         case SkSLType::kFloat3x3:
140             return 12 * sizeof(float);
141         case SkSLType::kHalf4x4: // fall through
142         case SkSLType::kFloat4x4:
143             return 16 * sizeof(float);
144 
145         // This query is only valid for certain types.
146         case SkSLType::kVoid:
147         case SkSLType::kBool:
148         case SkSLType::kBool2:
149         case SkSLType::kBool3:
150         case SkSLType::kBool4:
151         case SkSLType::kTexture2DSampler:
152         case SkSLType::kTextureExternalSampler:
153         case SkSLType::kTexture2DRectSampler:
154         case SkSLType::kSampler:
155         case SkSLType::kTexture2D:
156         case SkSLType::kInput:
157             break;
158     }
159     SK_ABORT("Unexpected type");
160 }
161 
162 // Given the current offset into the ubo data, calculate the offset for the uniform we're trying to
163 // add taking into consideration all alignment requirements. The uniformOffset is set to the offset
164 // for the new uniform, and currentOffset is updated to be the offset to the end of the new uniform.
get_aligned_offset(uint32_t * currentOffset,SkSLType type,int arrayCount,int layout)165 static uint32_t get_aligned_offset(uint32_t* currentOffset,
166                                    SkSLType type,
167                                    int arrayCount,
168                                    int layout) {
169     uint32_t alignmentMask = sksltype_to_alignment_mask(type);
170     // For std140 layout we must make arrays align to 16 bytes.
171     // TODO(skia:13380): make sure 2x3 and 3x2 matrices are handled properly once SkSLType adds
172     // support for non-square matrices
173     if (layout == GrVkUniformHandler::kStd140Layout &&
174         (arrayCount || type == SkSLType::kFloat2x2 || type == SkSLType::kHalf2x2)) {
175         alignmentMask = 0xF;
176     }
177     uint32_t offsetDiff = *currentOffset & alignmentMask;
178     if (offsetDiff != 0) {
179         offsetDiff = alignmentMask - offsetDiff + 1;
180     }
181     int32_t uniformOffset = *currentOffset + offsetDiff;
182     SkASSERT(sizeof(float) == 4);
183     if (arrayCount) {
184         // TODO: this shouldn't be necessary for std430
185         uint32_t elementSize = std::max<uint32_t>(16, sksltype_to_vk_size(type, layout));
186         SkASSERT(0 == (elementSize & 0xF));
187         *currentOffset = uniformOffset + elementSize * arrayCount;
188     } else {
189         *currentOffset = uniformOffset + sksltype_to_vk_size(type, layout);
190     }
191     return uniformOffset;
192 }
193 
~GrVkUniformHandler()194 GrVkUniformHandler::~GrVkUniformHandler() {
195     for (VkUniformInfo& sampler : fSamplers.items()) {
196         if (sampler.fImmutableSampler) {
197             sampler.fImmutableSampler->unref();
198             sampler.fImmutableSampler = nullptr;
199         }
200     }
201 }
202 
internalAddUniformArray(const GrProcessor * owner,uint32_t visibility,SkSLType type,const char * name,bool mangleName,int arrayCount,const char ** outName)203 GrGLSLUniformHandler::UniformHandle GrVkUniformHandler::internalAddUniformArray(
204                                                                    const GrProcessor* owner,
205                                                                    uint32_t visibility,
206                                                                    SkSLType type,
207                                                                    const char* name,
208                                                                    bool mangleName,
209                                                                    int arrayCount,
210                                                                    const char** outName) {
211     SkASSERT(name && strlen(name));
212     SkASSERT(SkSLTypeCanBeUniformValue(type));
213 
214     // TODO this is a bit hacky, lets think of a better way.  Basically we need to be able to use
215     // the uniform view matrix name in the GP, and the GP is immutable so it has to tell the PB
216     // exactly what name it wants to use for the uniform view matrix.  If we prefix anythings, then
217     // the names will mismatch.  I think the correct solution is to have all GPs which need the
218     // uniform view matrix, they should upload the view matrix in their setData along with regular
219     // uniforms.
220     char prefix = 'u';
221     if ('u' == name[0] || !strncmp(name, GR_NO_MANGLE_PREFIX, strlen(GR_NO_MANGLE_PREFIX))) {
222         prefix = '\0';
223     }
224     SkString resolvedName = fProgramBuilder->nameVariable(prefix, name, mangleName);
225 
226     VkUniformInfo tempInfo;
227     tempInfo.fVariable = GrShaderVar{std::move(resolvedName),
228                                      type,
229                                      GrShaderVar::TypeModifier::None,
230                                      arrayCount};
231 
232     tempInfo.fVisibility = visibility;
233     tempInfo.fOwner      = owner;
234     tempInfo.fRawName    = SkString(name);
235 
236     for (int layout = 0; layout < kLayoutCount; ++layout) {
237         tempInfo.fOffsets[layout] = get_aligned_offset(&fCurrentOffsets[layout],
238                                                        type,
239                                                        arrayCount,
240                                                        layout);
241     }
242 
243     fUniforms.push_back(tempInfo);
244 
245     if (outName) {
246         *outName = fUniforms.back().fVariable.c_str();
247     }
248 
249     return GrGLSLUniformHandler::UniformHandle(fUniforms.count() - 1);
250 }
251 
addSampler(const GrBackendFormat & backendFormat,GrSamplerState state,const skgpu::Swizzle & swizzle,const char * name,const GrShaderCaps * shaderCaps)252 GrGLSLUniformHandler::SamplerHandle GrVkUniformHandler::addSampler(
253         const GrBackendFormat& backendFormat, GrSamplerState state, const skgpu::Swizzle& swizzle,
254         const char* name, const GrShaderCaps* shaderCaps) {
255     SkASSERT(name && strlen(name));
256 
257     const char prefix = 'u';
258     SkString mangleName = fProgramBuilder->nameVariable(prefix, name, /*mangle=*/true);
259 
260     SkString layoutQualifier;
261     layoutQualifier.appendf("set=%d, binding=%d", kSamplerDescSet, fSamplers.count());
262 
263     VkUniformInfo tempInfo;
264     tempInfo.fVariable =
265             GrShaderVar{std::move(mangleName),
266                         SkSLCombinedSamplerTypeForTextureType(backendFormat.textureType()),
267                         GrShaderVar::TypeModifier::Uniform,
268                         GrShaderVar::kNonArray,
269                         std::move(layoutQualifier),
270                         SkString()};
271 
272     tempInfo.fVisibility = kFragment_GrShaderFlag;
273     tempInfo.fOwner      = nullptr;
274     tempInfo.fRawName    = SkString(name);
275     tempInfo.fOffsets[0] = 0;
276     tempInfo.fOffsets[1] = 0;
277 
278     fSamplers.push_back(tempInfo);
279 
280     // Check if we are dealing with an external texture and store the needed information if so.
281     auto ycbcrInfo = backendFormat.getVkYcbcrConversionInfo();
282     if (ycbcrInfo && ycbcrInfo->isValid()) {
283         GrVkGpu* gpu = static_cast<GrVkPipelineStateBuilder*>(fProgramBuilder)->gpu();
284         GrVkSampler* sampler = gpu->resourceProvider().findOrCreateCompatibleSampler(state,
285                                                                                      *ycbcrInfo);
286         fSamplers.back().fImmutableSampler = sampler;
287         if (!sampler) {
288             return {};
289         }
290     }
291 
292     fSamplerSwizzles.push_back(swizzle);
293     SkASSERT(fSamplerSwizzles.size() == fSamplers.count());
294     return GrGLSLUniformHandler::SamplerHandle(fSamplers.count() - 1);
295 }
296 
addInputSampler(const skgpu::Swizzle & swizzle,const char * name)297 GrGLSLUniformHandler::SamplerHandle GrVkUniformHandler::addInputSampler(
298             const skgpu::Swizzle& swizzle, const char* name) {
299     SkASSERT(name && strlen(name));
300     SkASSERT(fInputUniform.fVariable.getType() == SkSLType::kVoid);
301 
302     const char prefix = 'u';
303     SkString mangleName = fProgramBuilder->nameVariable(prefix, name, /*mangle=*/true);
304 
305     SkString layoutQualifier;
306     layoutQualifier.appendf("input_attachment_index=%d, set=%d, binding=%d",
307                             kDstInputAttachmentIndex, kInputDescSet, kInputBinding);
308 
309     fInputUniform = {
310             GrShaderVar{std::move(mangleName), SkSLType::kInput, GrShaderVar::TypeModifier::Uniform,
311                         GrShaderVar::kNonArray, std::move(layoutQualifier), SkString()},
312             kFragment_GrShaderFlag, nullptr, SkString(name)};
313     fInputSwizzle = swizzle;
314     return GrGLSLUniformHandler::SamplerHandle(0);
315 }
316 
appendUniformDecls(GrShaderFlags visibility,SkString * out) const317 void GrVkUniformHandler::appendUniformDecls(GrShaderFlags visibility, SkString* out) const {
318     for (const VkUniformInfo& sampler : fSamplers.items()) {
319         SkASSERT(sampler.fVariable.getType() == SkSLType::kTexture2DSampler ||
320                  sampler.fVariable.getType() == SkSLType::kTextureExternalSampler);
321         if (visibility == sampler.fVisibility) {
322             sampler.fVariable.appendDecl(fProgramBuilder->shaderCaps(), out);
323             out->append(";\n");
324         }
325     }
326     if (fInputUniform.fVariable.getType() == SkSLType::kInput) {
327         if (visibility == fInputUniform.fVisibility) {
328             SkASSERT(visibility == kFragment_GrShaderFlag);
329             fInputUniform.fVariable.appendDecl(fProgramBuilder->shaderCaps(), out);
330             out->append(";\n");
331         }
332     }
333 
334 #ifdef SK_DEBUG
335     bool firstOffsetCheck = false;
336     for (const VkUniformInfo& localUniform : fUniforms.items()) {
337         if (!firstOffsetCheck) {
338             // Check to make sure we are starting our offset at 0 so the offset qualifier we
339             // set on each variable in the uniform block is valid.
340             SkASSERT(0 == localUniform.fOffsets[kStd140Layout] &&
341                      0 == localUniform.fOffsets[kStd430Layout]);
342             firstOffsetCheck = true;
343         }
344     }
345 #endif
346 
347     // At this point we determine whether we'll be using push constants based on the
348     // uniforms set so far. Later checks will use the internal bool we set here to
349     // keep things consistent.
350     this->determineIfUsePushConstants();
351     SkString uniformsString;
352     for (const VkUniformInfo& localUniform : fUniforms.items()) {
353         if (visibility & localUniform.fVisibility) {
354             if (SkSLTypeCanBeUniformValue(localUniform.fVariable.getType())) {
355                 Layout layout = fUsePushConstants ? kStd430Layout : kStd140Layout;
356                 uniformsString.appendf("layout(offset=%d) ", localUniform.fOffsets[layout]);
357                 localUniform.fVariable.appendDecl(fProgramBuilder->shaderCaps(), &uniformsString);
358                 uniformsString.append(";\n");
359             }
360         }
361     }
362 
363     if (!uniformsString.isEmpty()) {
364         if (fUsePushConstants) {
365             out->append("layout (push_constant) ");
366         } else {
367             out->appendf("layout (set=%d, binding=%d) ",
368                          kUniformBufferDescSet, kUniformBinding);
369         }
370         out->append("uniform uniformBuffer\n{\n");
371         out->appendf("%s\n};\n", uniformsString.c_str());
372     }
373 }
374 
getRTFlipOffset() const375 uint32_t GrVkUniformHandler::getRTFlipOffset() const {
376     Layout layout = fUsePushConstants ? kStd430Layout : kStd140Layout;
377     uint32_t currentOffset = fCurrentOffsets[layout];
378     return get_aligned_offset(&currentOffset, SkSLType::kFloat2, 0, layout);
379 }
380 
determineIfUsePushConstants() const381 void GrVkUniformHandler::determineIfUsePushConstants() const {
382     // We may insert a uniform for flipping origin-sensitive language features (e.g. sk_FragCoord).
383     // We won't know that for sure until then but we need to make this determination now,
384     // so assume we will need it.
385     static constexpr uint32_t kPad = 2*sizeof(float);
386     fUsePushConstants =
387             fCurrentOffsets[kStd430Layout] > 0 &&
388             fCurrentOffsets[kStd430Layout] + kPad <= fProgramBuilder->caps()->maxPushConstantsSize();
389 }
390