| 1 |
/* |
| 2 |
* Copyright 2021 Google LLC |
| 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 |
#ifndef skgpu_UniformManager_DEFINED |
| 9 |
#define skgpu_UniformManager_DEFINED |
| 10 |
|
| 11 |
#include "include/core/SkM44.h" |
| 12 |
#include "include/core/SkMatrix.h" |
| 13 |
#include "include/core/SkPoint.h" |
| 14 |
#include "include/core/SkPoint3.h" |
| 15 |
#include "include/core/SkRect.h" |
| 16 |
#include "include/core/SkRefCnt.h" |
| 17 |
#include "include/core/SkSize.h" |
| 18 |
#include "include/core/SkSpan.h" |
| 19 |
#include "include/private/base/SkAlign.h" |
| 20 |
#include "include/private/base/SkMath.h" |
| 21 |
#include "include/private/base/SkTArray.h" |
| 22 |
#include "src/base/SkHalf.h" |
| 23 |
#include "src/base/SkMathPriv.h" |
| 24 |
#include "src/core/SkColorData.h" |
| 25 |
#include "src/core/SkMatrixPriv.h" |
| 26 |
#include "src/core/SkSLTypeShared.h" |
| 27 |
#include "src/gpu/graphite/ResourceTypes.h" |
| 28 |
#include "src/gpu/graphite/Uniform.h" |
| 29 |
|
| 30 |
#include <algorithm> |
| 31 |
#include <memory> |
| 32 |
|
| 33 |
namespace skgpu::graphite { |
| 34 |
|
| 35 |
class UniformDataBlock; |
| 36 |
|
| 37 |
/** |
| 38 |
* Layout::kStd140 |
| 39 |
* =============== |
| 40 |
* |
| 41 |
* From OpenGL Specification Section 7.6.2.2 "Standard Uniform Block Layout" |
| 42 |
* [https://registry.khronos.org/OpenGL/specs/gl/glspec45.core.pdf#page=159]: |
| 43 |
* 1. If the member is a scalar consuming N basic machine units, the base alignment is N. |
| 44 |
* 2. If the member is a two- or four-component vector with components consuming N basic machine |
| 45 |
* units, the base alignment is 2N or 4N, respectively. |
| 46 |
* 3. If the member is a three-component vector with components consuming N |
| 47 |
* basic machine units, the base alignment is 4N. |
| 48 |
* 4. If the member is an array of scalars or vectors, the base alignment and array |
| 49 |
* stride are set to match the base alignment of a single array element, according |
| 50 |
* to rules (1), (2), and (3), and rounded up to the base alignment of a vec4. The |
| 51 |
* array may have padding at the end; the base offset of the member following |
| 52 |
* the array is rounded up to the next multiple of the base alignment. |
| 53 |
* 5. If the member is a column-major matrix with C columns and R rows, the |
| 54 |
* matrix is stored identically to an array of C column vectors with R components each, |
| 55 |
* according to rule (4). |
| 56 |
* 6. If the member is an array of S column-major matrices with C columns and |
| 57 |
* R rows, the matrix is stored identically to a row of S × C column vectors |
| 58 |
* with R components each, according to rule (4). |
| 59 |
* 7. If the member is a row-major matrix with C columns and R rows, the matrix |
| 60 |
* is stored identically to an array of R row vectors with C components each, |
| 61 |
* according to rule (4). |
| 62 |
* 8. If the member is an array of S row-major matrices with C columns and R |
| 63 |
* rows, the matrix is stored identically to a row of S × R row vectors with C |
| 64 |
* components each, according to rule (4). |
| 65 |
* 9. If the member is a structure, the base alignment of the structure is N, where |
| 66 |
* N is the largest base alignment value of any of its members, and rounded |
| 67 |
* up to the base alignment of a vec4. The individual members of this substructure are then |
| 68 |
* assigned offsets by applying this set of rules recursively, |
| 69 |
* where the base offset of the first member of the sub-structure is equal to the |
| 70 |
* aligned offset of the structure. The structure may have padding at the end; |
| 71 |
* the base offset of the member following the sub-structure is rounded up to |
| 72 |
* the next multiple of the base alignment of the structure. |
| 73 |
* 10. If the member is an array of S structures, the S elements of the array are laid |
| 74 |
* out in order, according to rule (9). |
| 75 |
* |
| 76 |
* Layout::kStd430 |
| 77 |
* =============== |
| 78 |
* |
| 79 |
* When using the std430 storage layout, shader storage blocks will be laid out in buffer storage |
| 80 |
* identically to uniform and shader storage blocks using the std140 layout, except that the base |
| 81 |
* alignment and stride of arrays of scalars and vectors in rule 4 and of structures in rule 9 are |
| 82 |
* not rounded up a multiple of the base alignment of a vec4. |
| 83 |
* |
| 84 |
* NOTE: While not explicitly stated, the layout rules for WebGPU and WGSL are identical to std430 |
| 85 |
* for SSBOs and nearly identical to std140 for UBOs. The default mat2x2 type is treated as two |
| 86 |
* float2's (not an array), so its size is 16 and alignment is 8 (vs. a size of 32 and alignment of |
| 87 |
* 16 in std140). When emitting WGSL from SkSL, prepareUniformPolyfillsForInterfaceBlock() defined |
| 88 |
* in WGSLCodeGenerator, will modify the type declaration to match std140 exactly. This allows the |
| 89 |
* UniformManager and UniformOffsetCalculator to avoid having WebGPU-specific layout rules |
| 90 |
* (whereas SkSL::MemoryLayout has more complete rules). |
| 91 |
* |
| 92 |
* Layout::kMetal |
| 93 |
* =============== |
| 94 |
* |
| 95 |
* SkSL converts its types to the non-packed SIMD vector types in MSL. The size and alignment rules |
| 96 |
* are equivalent to std430 with the exception of half3 and float3. In std430, the size consumed |
| 97 |
* by non-array uniforms of these types is 3N while Metal consumes 4N (which is equal to the |
| 98 |
* alignment of a vec3 in both Layouts). |
| 99 |
* |
| 100 |
* Half vs. Float Uniforms |
| 101 |
* ======================= |
| 102 |
* |
| 103 |
* Regardless of the precision when the shader is executed, std140 and std430 layouts consume |
| 104 |
* "half"-based uniforms in full 32-bit precision. Metal consumes "half"-based uniforms expecting |
| 105 |
* them to have already been converted to f16. WebGPU has an extension to support f16 types, which |
| 106 |
* behave like this, but we do not currently utilize it. |
| 107 |
* |
| 108 |
* The rules for std430 can be easily extended to f16 by applying N = 2 instead of N = 4 for the |
| 109 |
* base primitive alignment. The rules for std140 can be extended to f16 similarly except that |
| 110 |
* any alignment rounded up to vec4 always refers to vec4<f32> == 16, even if the component type |
| 111 |
* were defined in terms of f16. |
| 112 |
* |
| 113 |
* NOTE: This could also apply to the int vs. short or uint vs. ushort types, but these smaller |
| 114 |
* integer types are not supported on all platforms as uniforms. We disallow short integer uniforms |
| 115 |
* entirely, and if the data savings are required, packing should be implemented manually. |
| 116 |
* Short integer vertex attributes are supported when the vector type lets it pack into 32 bits |
| 117 |
* (e.g. int16x2 or int8x4). |
| 118 |
* |
| 119 |
* |
| 120 |
* Generalized Layout Rules |
| 121 |
* ======================== |
| 122 |
* |
| 123 |
* From the Layout descriptions above, the following simpler rules are sufficient: |
| 124 |
* |
| 125 |
* 1. If the base primitive type is "half" and the Layout expects half floats, N = 2; else, N = 4. |
| 126 |
* |
| 127 |
* 2. For arrays of scalars or vectors (with # of components, M = 1,2,3,4): |
| 128 |
* a. If arrays must be aligned on 16 byte boundaries, then align and stride = 16 |
| 129 |
* (equivalent to vec4 alignment when N=4). |
| 130 |
* b. Otherwise, the align and stride = SkNextPow2(M)*N (e.g. N,2N,4N,4N). |
| 131 |
* |
| 132 |
* In both cases, the total size required for the uniform is "array size"*stride. |
| 133 |
* |
| 134 |
* 3. For single scalars or vectors (M = 1,2,3,4), the align is SkNextPow2(M)*N (e.g. N,2N,4N,4N). |
| 135 |
* a. If M = 3 and the Layout aligns the size with the alignment, the size is 4*N and N |
| 136 |
* padding bytes must be zero'ed out afterwards. |
| 137 |
* b. Otherwise, the size = M*N |
| 138 |
* |
| 139 |
* 4. The starting offset to write data is the current offset aligned to the calculated align value. |
| 140 |
* The current offset is then incremented by the total size of the uniform. |
| 141 |
* |
| 142 |
* For arrays and padded vec3's, the padding is included in the stride and total size, meeting |
| 143 |
* the requirements of the original rule 4 in std140. When a single float3 that is not padded |
| 144 |
* is written, the next offset only advances 12 bytes allowing a smaller type to pack tightly |
| 145 |
* next to the Z coordinate. |
| 146 |
* |
| 147 |
* When N = 4, the CPU and GPU primitives are compatible, regardless of being float, int, or uint. |
| 148 |
* Contiguous ranges between any padding (for alignment or for array stride) can be memcpy'ed. |
| 149 |
* When N = 2, the CPU data is float and the GPU data f16, so values must be converted one primitive |
| 150 |
* at a time using SkFloatToHalf or skvx::to_half. |
| 151 |
* |
| 152 |
* The UniformManager will zero out any padding bytes (either prepended for starting alignment, |
| 153 |
* or appended for stride alignment). This is so that the final byte array can be hashed for uniform |
| 154 |
* value de-duplication before uploading to the GPU. |
| 155 |
* |
| 156 |
* While SkSL supports non-square matrices, the SkSLType enum and Graphite only expose support for |
| 157 |
* square matrices. Graphite assumes all matrix uniforms are in column-major order. This matches the |
| 158 |
* data layout of SkM44 already and UniformManager automatically transposes SkMatrix (which is in |
| 159 |
* row-major data) to be column-major. Thus, for layout purposes, a matrix or an array of matrices |
| 160 |
* can be laid out equivalently to an array of the column type with an array count multiplied by the |
| 161 |
* number of columns. |
| 162 |
*/ |
| 163 |
namespace LayoutRules { |
| 164 |
// The three diverging behaviors across the different Layouts: |
| 165 |
static constexpr bool PadVec3Size(Layout layout) { return layout == Layout::kMetal; } |
| 166 |
static constexpr bool AlignArraysTo16(Layout layout) { return layout == Layout::kStd140 || |
| 167 |
layout == Layout::kStd140_F16; } |
| 168 |
static constexpr bool UseFullPrecision(Layout layout) { return layout == Layout::kStd140 || |
| 169 |
layout == Layout::kStd430; } |
| 170 |
} |
| 171 |
|
| 172 |
class UniformOffsetCalculator { |
| 173 |
public: |
| 174 |
UniformOffsetCalculator() = default; |
| 175 |
|
| 176 |
static UniformOffsetCalculator ForTopLevel(Layout layout, int offset = 0) { |
| 177 |
return UniformOffsetCalculator(layout, offset, /*reqAlignment=*/1); |
| 178 |
} |
| 179 |
|
| 180 |
static UniformOffsetCalculator ForStruct(Layout layout) { |
| 181 |
const int reqAlignment = LayoutRules::AlignArraysTo16(layout) ? 16 : 1; |
| 182 |
return UniformOffsetCalculator(layout, /*offset=*/0, reqAlignment); |
| 183 |
} |
| 184 |
|
| 185 |
Layout layout() const { return fLayout; } |
| 186 |
|
| 187 |
// NOTE: The returned size represents the last consumed byte, if the recorded |
| 188 |
// uniforms are embedded within a struct, this will need to be rounded up to a multiple of |
| 189 |
// requiredAlignment(). |
| 190 |
int size() const { return fOffset; } |
| 191 |
int requiredAlignment() const { return fReqAlignment; } |
| 192 |
|
| 193 |
// Returns the correctly aligned offset to accommodate `count` instances of `type` and |
| 194 |
// advances the internal offset. |
| 195 |
// |
| 196 |
// After a call to this method, `size()` will return the offset to the end of `count` instances |
| 197 |
// of `type` (while the return value equals the aligned start offset). Subsequent calls will |
| 198 |
// calculate the new start offset starting at `size()`. |
| 199 |
int advanceOffset(SkSLType type, int count = Uniform::kNonArray); |
| 200 |
|
| 201 |
// Returns the correctly aligned offset to accommodate `count` instances of a custom struct |
| 202 |
// type that has had its own fields passed into the `substruct` offset calculator. |
| 203 |
// |
| 204 |
// After a call to this method, `size()` will return the offset to the end of `count` instances |
| 205 |
// of the struct types (while the return value equals the aligned start offset). This includes |
| 206 |
// any required padding of the struct size per rule #9. |
| 207 |
int advanceStruct(const UniformOffsetCalculator& substruct, int count = Uniform::kNonArray); |
| 208 |
|
| 209 |
private: |
| 210 |
UniformOffsetCalculator(Layout layout, int offset, int reqAlignment) |
| 211 |
: fLayout(layout), fOffset(offset), fReqAlignment((reqAlignment)) {} |
| 212 |
|
| 213 |
Layout fLayout = Layout::kInvalid; |
| 214 |
int fOffset = 0; |
| 215 |
int fReqAlignment = 1; |
| 216 |
}; |
| 217 |
|
| 218 |
class UniformManager { |
| 219 |
public: |
| 220 |
UniformManager(Layout layout) { this->resetWithNewLayout(layout); } |
| 221 |
|
| 222 |
void markOffset() { |
| 223 |
fEndPaintOffset = fStorage.size(); |
| 224 |
fEndPaintAlignment = fReqAlignment; |
| 225 |
SkDEBUGCODE(fMarkedOffsetCalculator = fOffsetCalculator;) |
| 226 |
} |
| 227 |
|
| 228 |
void alignForNonShading(int requiredAlignment) { |
| 229 |
this->alignTo(requiredAlignment); |
| 230 |
fNonShadingOffset = fStorage.size(); |
| 231 |
SkASSERT(SkIsPow2(requiredAlignment)); |
| 232 |
fReqAlignment = std::max(fReqAlignment, requiredAlignment); |
| 233 |
|
| 234 |
#ifdef SK_DEBUG |
| 235 |
fOffsetCalculator = UniformOffsetCalculator::ForTopLevel(fLayout); |
| 236 |
fExpectedUniforms = {}; |
| 237 |
fExpectedUniformIndex = 0; |
| 238 |
#endif |
| 239 |
// If we're rewinding, we shouldn't be using substructs. |
| 240 |
SkASSERT(fSubstructStartingOffset == -1); |
| 241 |
// Any struct should be closed. |
| 242 |
SkASSERT(fStructBaseAlignment == 0); |
| 243 |
} |
| 244 |
|
| 245 |
SkSpan<const char> finish(int subspanStart = 0) { |
| 246 |
this->alignTo(fReqAlignment); |
| 247 |
fStorageHighWaterMark = std::max(fStorageHighWaterMark,fStorage.size()); |
| 248 |
return fStorage.empty() ? |
| 249 |
SkSpan<const char>() : |
| 250 |
SkSpan<const char>(fStorage).subspan(static_cast<size_t>(subspanStart)); |
| 251 |
} |
| 252 |
|
| 253 |
SkSpan<const char> finishMarked() { |
| 254 |
return this->finish(fNonShadingOffset); |
| 255 |
} |
| 256 |
|
| 257 |
void resetWithNewLayout(Layout layout); |
| 258 |
void reset() { this->resetWithNewLayout(fLayout); } |
| 259 |
void rewindToMark(); |
| 260 |
|
| 261 |
Layout layout() const { return fLayout; } |
| 262 |
int size() const { return fStorage.size(); } |
| 263 |
|
| 264 |
void tryShrinkCapacity() { |
| 265 |
int halfCapacity = fStorage.capacity() / 2; |
| 266 |
if (fStorageHighWaterMark < halfCapacity) { |
| 267 |
fStorageHighWaterMark = 0; |
| 268 |
SkASSERT(fStorage.empty()); |
| 269 |
fStorage.reserve_exact(halfCapacity); |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
// scalars |
| 274 |
void write(float f) { this->write<SkSLType::kFloat>(&f); } |
| 275 |
void write(int32_t i) { this->write<SkSLType::kInt >(&i); } |
| 276 |
void writeHalf(float f) { this->write<SkSLType::kHalf >(&f); } |
| 277 |
|
| 278 |
// [i|h]vec4 and arrays thereof (just add overloads as needed) |
| 279 |
void write(const SkPMColor4f& c) { this->write<SkSLType::kFloat4>(c.vec()); } |
| 280 |
void write(const SkRect& r) { this->write<SkSLType::kFloat4>(r.asScalars()); } |
| 281 |
void write(const SkV4& v) { this->write<SkSLType::kFloat4>(v.ptr()); } |
| 282 |
|
| 283 |
void write(const SkIRect& r) { this->write<SkSLType::kInt4>(&r); } |
| 284 |
|
| 285 |
void writeHalf(const SkPMColor4f& c) { this->write<SkSLType::kHalf4>(c.vec()); } |
| 286 |
void writeHalf(const SkRect& r) { this->write<SkSLType::kHalf4>(r.asScalars()); } |
| 287 |
void writeHalf(const SkV4& v) { this->write<SkSLType::kHalf4>(v.ptr()); } |
| 288 |
|
| 289 |
void writeArray(SkSpan<const SkV4> v) { |
| 290 |
this->writeArray<SkSLType::kFloat4>(v.data(), v.size()); |
| 291 |
} |
| 292 |
void writeArray(SkSpan<const SkPMColor4f> c) { |
| 293 |
this->writeArray<SkSLType::kFloat4>(c.data(), c.size()); |
| 294 |
} |
| 295 |
void writeHalfArray(SkSpan<const SkPMColor4f> c) { |
| 296 |
this->writeArray<SkSLType::kHalf4>(c.data(), c.size()); |
| 297 |
} |
| 298 |
|
| 299 |
// [i|h]vec3 |
| 300 |
void write(const SkV3& v) { this->write<SkSLType::kFloat3>(v.ptr()); } |
| 301 |
void write(const SkPoint3& p) { this->write<SkSLType::kFloat3>(&p); } |
| 302 |
|
| 303 |
void writeHalf(const SkV3& v) { this->write<SkSLType::kHalf3>(v.ptr()); } |
| 304 |
void writeHalf(const SkPoint3& p) { this->write<SkSLType::kHalf3>(&p); } |
| 305 |
|
| 306 |
// NOTE: 3-element vectors never pack efficiently in arrays, so avoid using them |
| 307 |
|
| 308 |
// [i|h]vec2 |
| 309 |
void write(const SkV2& v) { this->write<SkSLType::kFloat2>(v.ptr()); } |
| 310 |
void write(const SkSize& s) { this->write<SkSLType::kFloat2>(&s); } |
| 311 |
void write(const SkPoint& p) { this->write<SkSLType::kFloat2>(&p); } |
| 312 |
|
| 313 |
void write(const SkISize& s) { this->write<SkSLType::kInt2>(&s); } |
| 314 |
|
| 315 |
void writeHalf(const SkV2& v) { this->write<SkSLType::kHalf2>(v.ptr()); } |
| 316 |
void writeHalf(const SkSize& s) { this->write<SkSLType::kHalf2>(&s); } |
| 317 |
void writeHalf(const SkPoint& p) { this->write<SkSLType::kHalf2>(&p); } |
| 318 |
|
| 319 |
// NOTE: 2-element vectors don't pack efficiently in std140, so avoid using them |
| 320 |
|
| 321 |
// matrices |
| 322 |
void write(const SkM44& m) { |
| 323 |
// All Layouts treat a 4x4 column-major matrix as an array of vec4's, which is exactly how |
| 324 |
// SkM44 already stores its data. |
| 325 |
this->writeArray<SkSLType::kFloat4>(SkMatrixPriv::M44ColMajor(m), 4); |
| 326 |
} |
| 327 |
|
| 328 |
void writeHalf(const SkM44& m) { |
| 329 |
this->writeArray<SkSLType::kHalf4>(SkMatrixPriv::M44ColMajor(m), 4); |
| 330 |
} |
| 331 |
|
| 332 |
void write(const SkMatrix& m) { |
| 333 |
// SkMatrix is row-major, so rewrite to column major. All Layouts treat a 3x3 column |
| 334 |
// major matrix as an array of vec3's. |
| 335 |
float colMajor[9] = {m[0], m[3], m[6], |
| 336 |
m[1], m[4], m[7], |
| 337 |
m[2], m[5], m[8]}; |
| 338 |
this->writeArray<SkSLType::kFloat3>(colMajor, 3); |
| 339 |
} |
| 340 |
void writeHalf(const SkMatrix& m) { |
| 341 |
float colMajor[9] = {m[0], m[3], m[6], |
| 342 |
m[1], m[4], m[7], |
| 343 |
m[2], m[5], m[8]}; |
| 344 |
this->writeArray<SkSLType::kHalf3>(colMajor, 3); |
| 345 |
} |
| 346 |
|
| 347 |
// NOTE: 2x2 matrices can be manually packed the same or better as a vec4, so prefer that |
| 348 |
|
| 349 |
// This is a specialized uniform writing entry point intended to deduplicate the paint |
| 350 |
// color. If a more general system is required, the deduping logic can be added to the |
| 351 |
// other write methods (and this specialized method would be removed). |
| 352 |
void writePaintColor(const SkPMColor4f& color) { |
| 353 |
if (fWrotePaintColor) { |
| 354 |
// Validate expected uniforms, but don't write a second copy since the paint color |
| 355 |
// uniform can only ever be declared once in the final SkSL program. |
| 356 |
SkDEBUGCODE( |
| 357 |
this->checkExpected(/*dst=*/nullptr, SkSLType::kFloat4, Uniform::kNonArray)); |
| 358 |
} else { |
| 359 |
this->write<SkSLType::kFloat4>(&color); |
| 360 |
fWrotePaintColor = true; |
| 361 |
} |
| 362 |
} |
| 363 |
|
| 364 |
// Copy from `src` using Uniform array-count semantics. |
| 365 |
void write(const Uniform&, const void* src); |
| 366 |
|
| 367 |
// UniformManager has basic support for writing substructs with the caveats: |
| 368 |
// 1. The base alignment of the substruct must be known a priori so the first member can be |
| 369 |
// written immediately. |
| 370 |
// 2. Nested substructs are not supported (but could be if the padded-struct size was also |
| 371 |
// provided to endStruct()). |
| 372 |
// |
| 373 |
// Call beginStruct(baseAlignment) before writing the first field. Then call the regular |
| 374 |
// write functions for each of the substruct's fields in order. Lastly, call endStruct() to |
| 375 |
// go back to writing fields in the top-level interface block. |
| 376 |
void beginStruct(int baseAlignment) { |
| 377 |
SkDEBUGCODE(this->checkBeginStruct(baseAlignment)); // verifies baseAlignment matches layout |
| 378 |
|
| 379 |
this->alignTo(baseAlignment); |
| 380 |
fStructBaseAlignment = baseAlignment; |
| 381 |
fReqAlignment = std::max(fReqAlignment, baseAlignment); |
| 382 |
} |
| 383 |
void endStruct() { |
| 384 |
SkASSERT(fStructBaseAlignment >= 1); // Must have started a struct |
| 385 |
this->alignTo(fStructBaseAlignment); |
| 386 |
SkDEBUGCODE(this->checkEndStruct()); // validate after padding out to struct's alignment |
| 387 |
fStructBaseAlignment = 0; |
| 388 |
} |
| 389 |
|
| 390 |
// Debug-only functions to control uniform expectations. |
| 391 |
#ifdef SK_DEBUG |
| 392 |
bool isReset() const; |
| 393 |
void setExpectedUniforms(SkSpan<const Uniform> expected, bool isSubstruct); |
| 394 |
void doneWithExpectedUniforms(); |
| 395 |
#endif // SK_DEBUG |
| 396 |
|
| 397 |
private: |
| 398 |
// All public write() functions in UniformManager already match scalar/vector SkSLTypes or have |
| 399 |
// explicitly converted matrix SkSLTypes to a writeArray<column type> so this does not need to |
| 400 |
// check anything beyond half[2,3,4]. |
| 401 |
static constexpr bool IsHalfVector(SkSLType type) { |
| 402 |
return type >= SkSLType::kHalf && type <= SkSLType::kHalf4; |
| 403 |
} |
| 404 |
|
| 405 |
// Other than validation, actual layout doesn't care about 'type' and the logic can be |
| 406 |
// based on vector length and whether or not it's half or full precision. |
| 407 |
template <int N, bool Half> void write(const void* src, SkSLType type); |
| 408 |
template <int N, bool Half, bool Align16> |
| 409 |
void writeArray(const void* src, int count, SkSLType type); |
| 410 |
|
| 411 |
// Helpers to select dimensionality and convert to full precision if required by the Layout. |
| 412 |
template <SkSLType Type> void write(const void* src) { |
| 413 |
static constexpr int N = SkSLTypeVecLength(Type); |
| 414 |
if (IsHalfVector(Type) && !LayoutRules::UseFullPrecision(fLayout)) { |
| 415 |
this->write<N, /*Half=*/true>(src, Type); |
| 416 |
} else { |
| 417 |
this->write<N, /*Half=*/false>(src, Type); |
| 418 |
} |
| 419 |
} |
| 420 |
template <SkSLType Type> void writeArray(const void* src, int count) { |
| 421 |
static constexpr int N = SkSLTypeVecLength(Type); |
| 422 |
const bool align16 = LayoutRules::AlignArraysTo16(fLayout); |
| 423 |
if (IsHalfVector(Type) && !LayoutRules::UseFullPrecision(fLayout)) { |
| 424 |
if (align16) { |
| 425 |
this->writeArray<N, /*Half=*/true, /*Align16=*/true>(src, count, Type); |
| 426 |
} else { |
| 427 |
this->writeArray<N, /*Half=*/true, /*Align16=*/false>(src, count, Type); |
| 428 |
} |
| 429 |
} else { |
| 430 |
if (align16) { |
| 431 |
this->writeArray<N, /*Half=*/false, /*Align16=*/true>(src, count, Type); |
| 432 |
} else { |
| 433 |
this->writeArray<N, /*Half=*/false, /*Align16=*/false>(src, count, Type); |
| 434 |
} |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
// This is marked 'inline' so that it can be defined below with write() and writeArray() and |
| 439 |
// still link correctly. |
| 440 |
inline char* append(int alignment, int size); |
| 441 |
inline void alignTo(int alignment); |
| 442 |
|
| 443 |
skia_private::TArray<char> fStorage; |
| 444 |
int fStorageHighWaterMark = 0; |
| 445 |
|
| 446 |
Layout fLayout; |
| 447 |
|
| 448 |
int fReqAlignment = 1; // The proggresive alignment as we process uniforms |
| 449 |
int fEndPaintAlignment = 1; // The alignment at the end of the paint uniforms |
| 450 |
int fStructBaseAlignment = 0; // The base alignment of a struct. |
| 451 |
|
| 452 |
int fEndPaintOffset = 0; // The unaligned size of the paint uniforms |
| 453 |
int fNonShadingOffset = 0; // The aligned start of non-shading renderstep uniforms |
| 454 |
|
| 455 |
bool fWrotePaintColor = false; // The paint only adds its uniform once. |
| 456 |
|
| 457 |
// Debug-only verification that UniformOffsetCalculator is consistent and that write() calls |
| 458 |
// match the expected uniform declaration order. |
| 459 |
#ifdef SK_DEBUG |
| 460 |
UniformOffsetCalculator fOffsetCalculator; // should match implicit offsets from append() |
| 461 |
UniformOffsetCalculator fMarkedOffsetCalculator; // store the offset calculator at rewind |
| 462 |
UniformOffsetCalculator fSubstructCalculator; // 0-based, used when inside a substruct |
| 463 |
int fSubstructStartingOffset = -1; // offset of first field in fOffsetCalculator |
| 464 |
|
| 465 |
SkSpan<const Uniform> fExpectedUniforms; |
| 466 |
int fExpectedUniformIndex = 0; |
| 467 |
|
| 468 |
void checkExpected(const void* dst, SkSLType, int count); |
| 469 |
void checkBeginStruct(int baseAlignment); |
| 470 |
void checkEndStruct(); |
| 471 |
#endif // SK_DEBUG |
| 472 |
}; |
| 473 |
|
| 474 |
/////////////////////////////////////////////////////////////////////////////////////////////////// |
| 475 |
// Definitions |
| 476 |
|
| 477 |
// Shared helper for both write() and writeArray() |
| 478 |
template <int N, bool Half> |
| 479 |
struct LayoutTraits { |
| 480 |
static_assert(1 <= N && N <= 4); |
| 481 |
|
| 482 |
static constexpr int kElemSize = Half ? sizeof(SkHalf) : sizeof(float); |
| 483 |
static constexpr int kSize = N * kElemSize; |
| 484 |
static constexpr int kAlign = SkNextPow2_portable(N) * kElemSize; |
| 485 |
|
| 486 |
// Reads kSize bytes from 'src' and copies or converts (float->half) the N values |
| 487 |
// into 'dst'. Does not add any other padding that may depend on usage and Layout. |
| 488 |
static void Copy(const void* src, void* dst) { |
| 489 |
if constexpr (Half) { |
| 490 |
using VecF = skvx::Vec<SkNextPow2_portable(N), float>; |
| 491 |
VecF srcData; |
| 492 |
if constexpr (N == 3) { |
| 493 |
// Load the 3 values into a float4 to take advantage of vectorized conversion. |
| 494 |
// The 4th value will not be copied to dst. |
| 495 |
const float* srcF = static_cast<const float*>(src); |
| 496 |
srcData = VecF{srcF[0], srcF[1], srcF[2], 0.f}; |
| 497 |
} else { |
| 498 |
srcData = VecF::Load(src); |
| 499 |
} |
| 500 |
|
| 501 |
auto dstData = to_half(srcData); |
| 502 |
// NOTE: this is identical to Vec::store() for N=1,2,4 and correctly drops the 4th |
| 503 |
// lane when N=3. |
| 504 |
memcpy(dst, &dstData, kSize); |
| 505 |
} else { |
| 506 |
memcpy(dst, src, kSize); |
| 507 |
} |
| 508 |
} |
| 509 |
|
| 510 |
#ifdef SK_DEBUG |
| 511 |
static void Validate(const void* src, SkSLType type, Layout layout) { |
| 512 |
// Src validation |
| 513 |
SkASSERT(src); |
| 514 |
// All primitives on the CPU side should be 4 byte aligned |
| 515 |
SkASSERT(SkIsAlign4(reinterpret_cast<intptr_t>(src))); |
| 516 |
|
| 517 |
// Type and validation layout |
| 518 |
SkASSERT(SkSLTypeCanBeUniformValue(type)); |
| 519 |
SkASSERT(SkSLTypeVecLength(type) == N); // Matrix types should have been flattened already |
| 520 |
if constexpr (Half) { |
| 521 |
SkASSERT(SkSLTypeIsFloatType(type)); |
| 522 |
SkASSERT(!SkSLTypeIsFullPrecisionNumericType(type)); |
| 523 |
SkASSERT(!LayoutRules::UseFullPrecision(layout)); |
| 524 |
} else { |
| 525 |
SkASSERT(SkSLTypeIsFullPrecisionNumericType(type) || |
| 526 |
LayoutRules::UseFullPrecision(layout)); |
| 527 |
} |
| 528 |
} |
| 529 |
#endif |
| 530 |
}; |
| 531 |
|
| 532 |
template<int N, bool Half> |
| 533 |
void UniformManager::write(const void* src, SkSLType type) { |
| 534 |
using L = LayoutTraits<N, Half>; |
| 535 |
SkDEBUGCODE(L::Validate(src, type, fLayout);) |
| 536 |
|
| 537 |
// Layouts diverge in how vec3 size is determined for non-array usage |
| 538 |
char* dst = (N == 3 && LayoutRules::PadVec3Size(fLayout)) |
| 539 |
? this->append(L::kAlign, L::kSize + L::kElemSize) |
| 540 |
: this->append(L::kAlign, L::kSize); |
| 541 |
SkDEBUGCODE(this->checkExpected(dst, type, Uniform::kNonArray)); |
| 542 |
|
| 543 |
L::Copy(src, dst); |
| 544 |
if (N == 3 && LayoutRules::PadVec3Size(fLayout)) { |
| 545 |
memset(dst + L::kSize, 0, L::kElemSize); |
| 546 |
} |
| 547 |
} |
| 548 |
|
| 549 |
template<int N, bool Half, bool Align16> |
| 550 |
void UniformManager::writeArray(const void* src, int count, SkSLType type) { |
| 551 |
using L = LayoutTraits<N, Half>; |
| 552 |
static constexpr int kSrcStride = N * 4; // Source data is always in multiples of 4 bytes. |
| 553 |
|
| 554 |
SkDEBUGCODE(L::Validate(src, type, fLayout);) |
| 555 |
SkASSERT(count > 0); |
| 556 |
SkASSERT(Align16 == LayoutRules::AlignArraysTo16(fLayout)); |
| 557 |
|
| 558 |
if constexpr (Half || N == 3 || (N != 4 && Align16)) { |
| 559 |
// Size (H|F) Align (H|F) Padding (H|F) Align16-Padding (H|F) |
| 560 |
// N = 1 2|4 2|4 0|0(*) 14|12 |
| 561 |
// N = 2 4|8 4|8 0|0(*) 12|8 |
| 562 |
// N = 3 6|12 8|16 2|4 10|4 |
| 563 |
// N = 4 8|16 8|16 0|0(*) 8|0(*) |
| 564 |
// Padding entries marked with (*) represent cases that fall into the else block below. |
| 565 |
// All other cases need per-element half conversion and/or per-element padding added. |
| 566 |
static constexpr int kStride = Align16 ? 16 : L::kAlign; |
| 567 |
|
| 568 |
const char* srcBytes = reinterpret_cast<const char*>(src); |
| 569 |
char* dst = this->append(kStride, kStride*count); |
| 570 |
SkDEBUGCODE(this->checkExpected(dst, type, count)); |
| 571 |
|
| 572 |
for (int i = 0; i < count; ++i) { |
| 573 |
L::Copy(srcBytes, dst); |
| 574 |
if constexpr (kStride - L::kSize > 0) { |
| 575 |
memset(dst + L::kSize, 0, kStride - L::kSize); |
| 576 |
} |
| 577 |
|
| 578 |
dst += kStride; |
| 579 |
srcBytes += kSrcStride; |
| 580 |
} |
| 581 |
} else { |
| 582 |
// A dense array with no type conversion, so copy in one go. |
| 583 |
SkASSERT(L::kAlign == L::kSize && kSrcStride == L::kSize); |
| 584 |
char* dst = this->append(L::kAlign, L::kSize*count); |
| 585 |
SkDEBUGCODE(this->checkExpected(dst, type, count)); |
| 586 |
|
| 587 |
memcpy(dst, src, L::kSize*count); |
| 588 |
} |
| 589 |
} |
| 590 |
|
| 591 |
void UniformManager::alignTo(int alignment) { |
| 592 |
SkASSERT(alignment >= 1 && SkIsPow2(alignment)); |
| 593 |
if ((fStorage.size() & (alignment - 1)) != 0) { |
| 594 |
this->append(alignment, /*size=*/0); |
| 595 |
} |
| 596 |
} |
| 597 |
|
| 598 |
char* UniformManager::append(int alignment, int size) { |
| 599 |
// The base alignment for a struct should have been calculated for the current layout using |
| 600 |
// UniformOffsetCalculator, so every field appended within the struct should have an alignment |
| 601 |
// less than or equal to that base alignment. |
| 602 |
SkASSERT(fStructBaseAlignment <= 0 || alignment <= fStructBaseAlignment); |
| 603 |
|
| 604 |
const int offset = fStorage.size(); |
| 605 |
const int padding = SkAlignTo(offset, alignment) - offset; |
| 606 |
|
| 607 |
// These are just asserts not aborts because SkSL compilation imposes limits on the size of |
| 608 |
// runtime effect arrays, and internal shaders should not be using excessive lengths. |
| 609 |
SkASSERT(std::numeric_limits<int>::max() - alignment >= offset); |
| 610 |
SkASSERT(std::numeric_limits<int>::max() - size >= padding); |
| 611 |
|
| 612 |
char* dst = fStorage.push_back_n(size + padding); |
| 613 |
if (padding > 0) { |
| 614 |
memset(dst, 0, padding); |
| 615 |
dst += padding; |
| 616 |
} |
| 617 |
|
| 618 |
// For pow of 2, max is LCM. If that assumption changes, this should change as well. |
| 619 |
fReqAlignment = std::max(fReqAlignment, alignment); |
| 620 |
return dst; |
| 621 |
} |
| 622 |
|
| 623 |
} // namespace skgpu::graphite |
| 624 |
|
| 625 |
#endif // skgpu_UniformManager_DEFINED |