• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2018 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/effects/GrSkSLFP.h"
9 
10 #include "include/effects/SkRuntimeEffect.h"
11 #include "include/gpu/GrTexture.h"
12 #include "include/private/GrContext_Base.h"
13 #include "src/gpu/GrBaseContextPriv.h"
14 #include "src/sksl/SkSLUtil.h"
15 
16 #include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
17 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
18 #include "src/gpu/glsl/GrGLSLProgramBuilder.h"
19 
20 class GrGLSLSkSLFP : public GrGLSLFragmentProcessor {
21 public:
GrGLSLSkSLFP(SkSL::PipelineStageArgs && args)22     GrGLSLSkSLFP(SkSL::PipelineStageArgs&& args) : fArgs(std::move(args)) {}
23 
expandFormatArgs(const SkSL::String & raw,EmitArgs & args,std::vector<SkSL::Compiler::FormatArg>::const_iterator & fmtArg,const char * coordsName)24     SkSL::String expandFormatArgs(const SkSL::String& raw,
25                                   EmitArgs& args,
26                                   std::vector<SkSL::Compiler::FormatArg>::const_iterator& fmtArg,
27                                   const char* coordsName) {
28         SkSL::String result;
29         int substringStartIndex = 0;
30         for (size_t i = 0; i < raw.length(); ++i) {
31             char c = raw[i];
32             if (c == '%') {
33                 result += SkSL::StringFragment(raw.c_str() + substringStartIndex,
34                                                i - substringStartIndex);
35                 ++i;
36                 c = raw[i];
37                 switch (c) {
38                     case 's': {
39                         const SkSL::Compiler::FormatArg& arg = *fmtArg++;
40                         switch (arg.fKind) {
41                             case SkSL::Compiler::FormatArg::Kind::kInput:
42                                 result += args.fInputColor;
43                                 break;
44                             case SkSL::Compiler::FormatArg::Kind::kOutput:
45                                 result += args.fOutputColor;
46                                 break;
47                             case SkSL::Compiler::FormatArg::Kind::kCoords:
48                                 result += coordsName;
49                                 break;
50                             case SkSL::Compiler::FormatArg::Kind::kUniform:
51                                 result += args.fUniformHandler->getUniformCStr(
52                                                                        fUniformHandles[arg.fIndex]);
53                                 break;
54                             case SkSL::Compiler::FormatArg::Kind::kChildProcessor: {
55                                 SkSL::String coords = this->expandFormatArgs(arg.fCoords, args,
56                                                                              fmtArg, coordsName);
57                                 result += this->invokeChild(arg.fIndex, args, coords).c_str();
58                                 break;
59                             }
60                             case SkSL::Compiler::FormatArg::Kind::kFunctionName:
61                                 SkASSERT((int) fFunctionNames.size() > arg.fIndex);
62                                 result += fFunctionNames[arg.fIndex].c_str();
63                                 break;
64                         }
65                         break;
66                     }
67                     default:
68                         result += c;
69                 }
70                 substringStartIndex = i + 1;
71             }
72         }
73         result += SkSL::StringFragment(raw.c_str() + substringStartIndex,
74                                        raw.length() - substringStartIndex);
75         return result;
76     }
77 
emitCode(EmitArgs & args)78     void emitCode(EmitArgs& args) override {
79         const GrSkSLFP& fp = args.fFp.cast<GrSkSLFP>();
80         for (const auto& v : fp.fEffect->inputs()) {
81             if (v.fQualifier == SkRuntimeEffect::Variable::Qualifier::kUniform) {
82                 auto handle = args.fUniformHandler->addUniformArray(kFragment_GrShaderFlag,
83                                                                     v.fGPUType,
84                                                                     v.fName.c_str(),
85                                                                     v.isArray() ? v.fCount : 0);
86                 fUniformHandles.push_back(handle);
87             }
88         }
89         GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
90         SkASSERT(args.fTransformedCoords.count() == 1);
91         SkString coords = fragBuilder->ensureCoords2D(args.fTransformedCoords[0].fVaryingPoint);
92         std::vector<SkString> childNames;
93         // We need to ensure that we call invokeChild on each child FP at least once.
94         // Any child FP that isn't sampled won't trigger a call otherwise, leading to asserts later.
95         for (int i = 0; i < this->numChildProcessors(); ++i) {
96             (void)this->invokeChild(i, args, SkSL::String("_coords"));
97         }
98         for (const auto& f : fArgs.fFunctions) {
99             fFunctionNames.emplace_back();
100             auto fmtArgIter = f.fFormatArgs.cbegin();
101             SkSL::String body =
102                     this->expandFormatArgs(f.fBody.c_str(), args, fmtArgIter, coords.c_str());
103             SkASSERT(fmtArgIter == f.fFormatArgs.cend());
104             fragBuilder->emitFunction(f.fReturnType,
105                                       f.fName.c_str(),
106                                       f.fParameters.size(),
107                                       f.fParameters.data(),
108                                       body.c_str(),
109                                       &fFunctionNames.back());
110         }
111         auto fmtArgIter = fArgs.fFormatArgs.cbegin();
112         fragBuilder->codeAppend(this->expandFormatArgs(fArgs.fCode.c_str(), args, fmtArgIter,
113                                                        coords.c_str()).c_str());
114         SkASSERT(fmtArgIter == fArgs.fFormatArgs.cend());
115     }
116 
onSetData(const GrGLSLProgramDataManager & pdman,const GrFragmentProcessor & _proc)117     void onSetData(const GrGLSLProgramDataManager& pdman,
118                    const GrFragmentProcessor& _proc) override {
119         size_t uniIndex = 0;
120         const GrSkSLFP& outer = _proc.cast<GrSkSLFP>();
121         const uint8_t* inputs = outer.fInputs->bytes();
122         for (const auto& v : outer.fEffect->inputs()) {
123             if (v.fQualifier != SkRuntimeEffect::Variable::Qualifier::kUniform) {
124                 continue;
125             }
126 
127             const float* data = reinterpret_cast<const float*>(inputs + v.fOffset);
128             switch (v.fType) {
129                 case SkRuntimeEffect::Variable::Type::kFloat:
130                     pdman.set1fv(fUniformHandles[uniIndex++], v.fCount, data);
131                     break;
132                 case SkRuntimeEffect::Variable::Type::kFloat2:
133                     pdman.set2fv(fUniformHandles[uniIndex++], v.fCount, data);
134                     break;
135                 case SkRuntimeEffect::Variable::Type::kFloat3:
136                     pdman.set3fv(fUniformHandles[uniIndex++], v.fCount, data);
137                     break;
138                 case SkRuntimeEffect::Variable::Type::kFloat4:
139                     pdman.set4fv(fUniformHandles[uniIndex++], v.fCount, data);
140                     break;
141                 case SkRuntimeEffect::Variable::Type::kFloat2x2:
142                     pdman.setMatrix2fv(fUniformHandles[uniIndex++], v.fCount, data);
143                     break;
144                 case SkRuntimeEffect::Variable::Type::kFloat3x3:
145                     pdman.setMatrix3fv(fUniformHandles[uniIndex++], v.fCount, data);
146                     break;
147                 case SkRuntimeEffect::Variable::Type::kFloat4x4:
148                     pdman.setMatrix4fv(fUniformHandles[uniIndex++], v.fCount, data);
149                     break;
150                 default:
151                     SkDEBUGFAIL("Unsupported uniform type");
152                     break;
153             }
154         }
155     }
156 
157     // nearly-finished GLSL; still contains printf-style "%s" format tokens
158     SkSL::PipelineStageArgs fArgs;
159     std::vector<UniformHandle> fUniformHandles;
160     std::vector<SkString> fFunctionNames;
161 };
162 
Make(GrContext_Base * context,sk_sp<SkRuntimeEffect> effect,const char * name,sk_sp<SkData> inputs,const SkMatrix * matrix)163 std::unique_ptr<GrSkSLFP> GrSkSLFP::Make(GrContext_Base* context, sk_sp<SkRuntimeEffect> effect,
164                                          const char* name, sk_sp<SkData> inputs,
165                                          const SkMatrix* matrix) {
166     if (inputs->size() != effect->inputSize()) {
167         return nullptr;
168     }
169     return std::unique_ptr<GrSkSLFP>(new GrSkSLFP(context->priv().caps()->refShaderCaps(),
170                                                   std::move(effect), name, std::move(inputs),
171                                                   matrix));
172 }
173 
GrSkSLFP(sk_sp<const GrShaderCaps> shaderCaps,sk_sp<SkRuntimeEffect> effect,const char * name,sk_sp<SkData> inputs,const SkMatrix * matrix)174 GrSkSLFP::GrSkSLFP(sk_sp<const GrShaderCaps> shaderCaps, sk_sp<SkRuntimeEffect> effect,
175                    const char* name, sk_sp<SkData> inputs, const SkMatrix* matrix)
176         : INHERITED(kGrSkSLFP_ClassID, kNone_OptimizationFlags)
177         , fShaderCaps(std::move(shaderCaps))
178         , fEffect(std::move(effect))
179         , fName(name)
180         , fInputs(std::move(inputs)) {
181     if (matrix) {
182         fCoordTransform = GrCoordTransform(*matrix);
183     }
184     this->addCoordTransform(&fCoordTransform);
185 }
186 
GrSkSLFP(const GrSkSLFP & other)187 GrSkSLFP::GrSkSLFP(const GrSkSLFP& other)
188         : INHERITED(kGrSkSLFP_ClassID, kNone_OptimizationFlags)
189         , fShaderCaps(other.fShaderCaps)
190         , fEffect(other.fEffect)
191         , fName(other.fName)
192         , fInputs(other.fInputs) {
193     SkASSERT(other.numCoordTransforms() == 1);
194     fCoordTransform = other.fCoordTransform;
195     this->addCoordTransform(&fCoordTransform);
196 }
197 
name() const198 const char* GrSkSLFP::name() const {
199     return fName;
200 }
201 
addChild(std::unique_ptr<GrFragmentProcessor> child)202 void GrSkSLFP::addChild(std::unique_ptr<GrFragmentProcessor> child) {
203     child->setSampledWithExplicitCoords(true);
204     this->registerChildProcessor(std::move(child));
205 }
206 
onCreateGLSLInstance() const207 GrGLSLFragmentProcessor* GrSkSLFP::onCreateGLSLInstance() const {
208     // Note: This is actually SkSL (again) but with inline format specifiers.
209     SkSL::PipelineStageArgs args;
210     SkAssertResult(fEffect->toPipelineStage(fInputs->data(), fShaderCaps.get(), &args));
211     return new GrGLSLSkSLFP(std::move(args));
212 }
213 
onGetGLSLProcessorKey(const GrShaderCaps & caps,GrProcessorKeyBuilder * b) const214 void GrSkSLFP::onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const {
215     // In the unlikely event of a hash collision, we also include the input size in the key.
216     // That ensures that we will (at worst) use the wrong program, but one that expects the same
217     // amount of input data.
218     b->add32(fEffect->hash());
219     b->add32(SkToU32(fInputs->size()));
220     const uint8_t* inputs = fInputs->bytes();
221     for (const auto& v : fEffect->inputs()) {
222         if (v.fQualifier != SkRuntimeEffect::Variable::Qualifier::kIn) {
223             continue;
224         }
225         // 'in' arrays are not supported
226         SkASSERT(!v.isArray());
227         switch (v.fType) {
228             case SkRuntimeEffect::Variable::Type::kBool:
229                 b->add32(inputs[v.fOffset]);
230                 break;
231             case SkRuntimeEffect::Variable::Type::kInt:
232             case SkRuntimeEffect::Variable::Type::kFloat:
233                 b->add32(*(int32_t*)(inputs + v.fOffset));
234                 break;
235             default:
236                 SkDEBUGFAIL("Unsupported input variable type");
237                 break;
238         }
239     }
240 }
241 
onIsEqual(const GrFragmentProcessor & other) const242 bool GrSkSLFP::onIsEqual(const GrFragmentProcessor& other) const {
243     const GrSkSLFP& sk = other.cast<GrSkSLFP>();
244     return fEffect->hash() == sk.fEffect->hash() && fInputs->equals(sk.fInputs.get());
245 }
246 
clone() const247 std::unique_ptr<GrFragmentProcessor> GrSkSLFP::clone() const {
248     std::unique_ptr<GrSkSLFP> result(new GrSkSLFP(*this));
249     for (int i = 0; i < this->numChildProcessors(); ++i) {
250         result->addChild(this->childProcessor(i).clone());
251     }
252     return std::unique_ptr<GrFragmentProcessor>(result.release());
253 }
254 
255 /**************************************************************************************************/
256 
257 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrSkSLFP);
258 
259 #if GR_TEST_UTILS
260 
261 #include "include/effects/SkArithmeticImageFilter.h"
262 #include "include/gpu/GrContext.h"
263 #include "src/gpu/effects/generated/GrConstColorProcessor.h"
264 
265 extern const char* SKSL_ARITHMETIC_SRC;
266 extern const char* SKSL_DITHER_SRC;
267 extern const char* SKSL_OVERDRAW_SRC;
268 
269 using Value = SkSL::Program::Settings::Value;
270 
TestCreate(GrProcessorTestData * d)271 std::unique_ptr<GrFragmentProcessor> GrSkSLFP::TestCreate(GrProcessorTestData* d) {
272     int type = d->fRandom->nextULessThan(3);
273     switch (type) {
274         case 0: {
275             static auto effect = std::get<0>(SkRuntimeEffect::Make(SkString(SKSL_DITHER_SRC)));
276             int rangeType = d->fRandom->nextULessThan(3);
277             auto result = GrSkSLFP::Make(d->context(), effect, "Dither",
278                                          SkData::MakeWithCopy(&rangeType, sizeof(rangeType)));
279             return std::unique_ptr<GrFragmentProcessor>(result.release());
280         }
281         case 1: {
282             static auto effect = std::get<0>(SkRuntimeEffect::Make(SkString(SKSL_ARITHMETIC_SRC)));
283             ArithmeticFPInputs inputs{d->fRandom->nextF(), d->fRandom->nextF(), d->fRandom->nextF(),
284                                       d->fRandom->nextF(), d->fRandom->nextBool()};
285             auto result = GrSkSLFP::Make(d->context(), effect, "Arithmetic",
286                                          SkData::MakeWithCopy(&inputs, sizeof(inputs)));
287             result->addChild(GrConstColorProcessor::Make(
288                     SK_PMColor4fWHITE, GrConstColorProcessor::InputMode::kIgnore));
289             return std::unique_ptr<GrFragmentProcessor>(result.release());
290         }
291         case 2: {
292             static auto effect = std::get<0>(SkRuntimeEffect::Make(SkString(SKSL_OVERDRAW_SRC)));
293             SkColor4f inputs[6];
294             for (int i = 0; i < 6; ++i) {
295                 inputs[i] = SkColor4f::FromBytes_RGBA(d->fRandom->nextU());
296             }
297             auto result = GrSkSLFP::Make(d->context(), effect, "Overdraw",
298                                          SkData::MakeWithCopy(&inputs, sizeof(inputs)));
299             return std::unique_ptr<GrFragmentProcessor>(result.release());
300         }
301     }
302     SK_ABORT("unreachable");
303 }
304 
305 #endif
306