blob: e97cfd7a8f6da426d087ec0e313dee76b42b5a06 [file] [log] [blame]
Ethan Nicholas762466e2017-06-29 10:03:38 -04001/*
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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLCPPCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -04009
Brian Osman1298bc42020-06-30 13:39:35 -040010#include "include/private/SkSLSampleUsage.h"
Michael Ludwig8f3a8362020-06-29 17:27:00 -040011#include "src/sksl/SkSLAnalysis.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050012#include "src/sksl/SkSLCPPUniformCTypes.h"
13#include "src/sksl/SkSLCompiler.h"
14#include "src/sksl/SkSLHCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040015
Michael Ludwig92e4c7f2018-08-30 16:08:18 -040016#include <algorithm>
17
Ethan Nicholas762466e2017-06-29 10:03:38 -040018namespace SkSL {
19
20static bool needs_uniform_var(const Variable& var) {
Ethan Nicholas5f9836e2017-12-20 15:16:33 -050021 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
22 var.fType.kind() != Type::kSampler_Kind;
Ethan Nicholas762466e2017-06-29 10:03:38 -040023}
24
25CPPCodeGenerator::CPPCodeGenerator(const Context* context, const Program* program,
26 ErrorReporter* errors, String name, OutputStream* out)
John Stiles50819422020-06-18 13:00:38 -040027 : INHERITED(context, program, errors, out)
28 , fName(std::move(name))
29 , fFullName(String::printf("Gr%s", fName.c_str()))
30 , fSectionAndParameterHelper(program, *errors) {
31 fLineEnding = "\n";
Ethan Nicholas13863662019-07-29 13:05:15 -040032 fTextureFunctionOverride = "sample";
Ethan Nicholas762466e2017-06-29 10:03:38 -040033}
34
35void CPPCodeGenerator::writef(const char* s, va_list va) {
36 static constexpr int BUFFER_SIZE = 1024;
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040037 va_list copy;
38 va_copy(copy, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040039 char buffer[BUFFER_SIZE];
John Stiles50819422020-06-18 13:00:38 -040040 int length = std::vsnprintf(buffer, BUFFER_SIZE, s, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040041 if (length < BUFFER_SIZE) {
42 fOut->write(buffer, length);
43 } else {
44 std::unique_ptr<char[]> heap(new char[length + 1]);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040045 vsprintf(heap.get(), s, copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040046 fOut->write(heap.get(), length);
47 }
z102.zhangd74f2c82018-08-10 09:08:47 +080048 va_end(copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040049}
50
51void CPPCodeGenerator::writef(const char* s, ...) {
52 va_list va;
53 va_start(va, s);
54 this->writef(s, va);
55 va_end(va);
56}
57
58void CPPCodeGenerator::writeHeader() {
59}
60
Ethan Nicholasf7b88202017-09-18 14:10:39 -040061bool CPPCodeGenerator::usesPrecisionModifiers() const {
62 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -040063}
64
Ethan Nicholasf7b88202017-09-18 14:10:39 -040065String CPPCodeGenerator::getTypeName(const Type& type) {
66 return type.name();
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040067}
Ethan Nicholasf7b88202017-09-18 14:10:39 -040068
Ethan Nicholas762466e2017-06-29 10:03:38 -040069void CPPCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
70 Precedence parentPrecedence) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040071 if (b.fOperator == Token::Kind::TK_PERCENT) {
Ethan Nicholas762466e2017-06-29 10:03:38 -040072 // need to use "%%" instead of "%" b/c the code will be inside of a printf
73 Precedence precedence = GetBinaryPrecedence(b.fOperator);
74 if (precedence >= parentPrecedence) {
75 this->write("(");
76 }
77 this->writeExpression(*b.fLeft, precedence);
78 this->write(" %% ");
79 this->writeExpression(*b.fRight, precedence);
80 if (precedence >= parentPrecedence) {
81 this->write(")");
82 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050083 } else if (b.fLeft->fKind == Expression::kNullLiteral_Kind ||
84 b.fRight->fKind == Expression::kNullLiteral_Kind) {
85 const Variable* var;
86 if (b.fLeft->fKind != Expression::kNullLiteral_Kind) {
87 SkASSERT(b.fLeft->fKind == Expression::kVariableReference_Kind);
88 var = &((VariableReference&) *b.fLeft).fVariable;
89 } else {
90 SkASSERT(b.fRight->fKind == Expression::kVariableReference_Kind);
91 var = &((VariableReference&) *b.fRight).fVariable;
92 }
93 SkASSERT(var->fType.kind() == Type::kNullable_Kind &&
94 var->fType.componentType() == *fContext.fFragmentProcessor_Type);
95 this->write("%s");
Brian Osman12c5d292020-07-13 16:11:35 -040096 const char* op = "";
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050097 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040098 case Token::Kind::TK_EQEQ:
Brian Osman12c5d292020-07-13 16:11:35 -040099 op = "!";
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500100 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400101 case Token::Kind::TK_NEQ:
Brian Osman12c5d292020-07-13 16:11:35 -0400102 op = "";
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500103 break;
104 default:
105 SkASSERT(false);
106 }
Brian Osman12c5d292020-07-13 16:11:35 -0400107 int childIndex = this->getChildFPIndex(*var);
108 fFormatArgs.push_back(String(op) + "_outer.childProcessor(" + to_string(childIndex) +
109 ") ? \"true\" : \"false\"");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400110 } else {
111 INHERITED::writeBinaryExpression(b, parentPrecedence);
112 }
113}
114
115void CPPCodeGenerator::writeIndexExpression(const IndexExpression& i) {
116 const Expression& base = *i.fBase;
117 if (base.fKind == Expression::kVariableReference_Kind) {
118 int builtin = ((VariableReference&) base).fVariable.fModifiers.fLayout.fBuiltin;
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400119 if (SK_TEXTURESAMPLERS_BUILTIN == builtin) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400120 this->write("%s");
121 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700122 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400123 "index into sk_TextureSamplers must be an integer literal");
124 return;
125 }
126 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
127 fFormatArgs.push_back(" fragBuilder->getProgramBuilder()->samplerVariable("
Stephen Whited523a062019-06-19 13:12:46 -0400128 "args.fTexSamplers[" + to_string(index) + "])");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400129 return;
130 }
131 }
132 INHERITED::writeIndexExpression(i);
133}
134
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400135static String default_value(const Type& type) {
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500136 if (type.fName == "bool") {
137 return "false";
138 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400139 switch (type.kind()) {
140 case Type::kScalar_Kind: return "0";
141 case Type::kVector_Kind: return type.name() + "(0)";
142 case Type::kMatrix_Kind: return type.name() + "(1)";
143 default: ABORT("unsupported default_value type\n");
144 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400145}
146
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500147static String default_value(const Variable& var) {
Brian Osman495993a2018-10-16 15:45:55 -0400148 if (var.fModifiers.fLayout.fCType == SkSL::Layout::CType::kSkPMColor4f) {
Brian Osmanf28e55d2018-10-03 16:35:54 -0400149 return "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}";
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500150 }
151 return default_value(var.fType);
152}
153
Ethan Nicholas762466e2017-06-29 10:03:38 -0400154static bool is_private(const Variable& var) {
155 return !(var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
156 !(var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
157 var.fStorage == Variable::kGlobal_Storage &&
158 var.fModifiers.fLayout.fBuiltin == -1;
159}
160
Michael Ludwiga4275592018-08-31 10:52:47 -0400161static bool is_uniform_in(const Variable& var) {
162 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
163 (var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
164 var.fType.kind() != Type::kSampler_Kind;
165}
166
Ethan Nicholasd608c092017-10-26 09:30:08 -0400167void CPPCodeGenerator::writeRuntimeValue(const Type& type, const Layout& layout,
168 const String& cppCode) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400169 if (type.isFloat()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400170 this->write("%f");
171 fFormatArgs.push_back(cppCode);
172 } else if (type == *fContext.fInt_Type) {
173 this->write("%d");
174 fFormatArgs.push_back(cppCode);
175 } else if (type == *fContext.fBool_Type) {
176 this->write("%s");
177 fFormatArgs.push_back("(" + cppCode + " ? \"true\" : \"false\")");
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400178 } else if (type == *fContext.fFloat2_Type || type == *fContext.fHalf2_Type) {
179 this->write(type.name() + "(%f, %f)");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400180 fFormatArgs.push_back(cppCode + ".fX");
181 fFormatArgs.push_back(cppCode + ".fY");
Ethan Nicholas82399462017-10-16 12:35:44 -0400182 } else if (type == *fContext.fFloat4_Type || type == *fContext.fHalf4_Type) {
183 this->write(type.name() + "(%f, %f, %f, %f)");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400184 switch (layout.fCType) {
185 case Layout::CType::kSkPMColor:
186 fFormatArgs.push_back("SkGetPackedR32(" + cppCode + ") / 255.0");
187 fFormatArgs.push_back("SkGetPackedG32(" + cppCode + ") / 255.0");
188 fFormatArgs.push_back("SkGetPackedB32(" + cppCode + ") / 255.0");
189 fFormatArgs.push_back("SkGetPackedA32(" + cppCode + ") / 255.0");
190 break;
Brian Osmanf28e55d2018-10-03 16:35:54 -0400191 case Layout::CType::kSkPMColor4f:
192 fFormatArgs.push_back(cppCode + ".fR");
193 fFormatArgs.push_back(cppCode + ".fG");
194 fFormatArgs.push_back(cppCode + ".fB");
195 fFormatArgs.push_back(cppCode + ".fA");
196 break;
Mike Reedb26b4e72020-01-22 14:31:21 -0500197 case Layout::CType::kSkV4:
198 fFormatArgs.push_back(cppCode + ".x");
199 fFormatArgs.push_back(cppCode + ".y");
200 fFormatArgs.push_back(cppCode + ".z");
201 fFormatArgs.push_back(cppCode + ".w");
Brian Salomoneca66b32019-06-01 11:18:15 -0400202 break;
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400203 case Layout::CType::kSkRect: // fall through
204 case Layout::CType::kDefault:
205 fFormatArgs.push_back(cppCode + ".left()");
206 fFormatArgs.push_back(cppCode + ".top()");
207 fFormatArgs.push_back(cppCode + ".right()");
208 fFormatArgs.push_back(cppCode + ".bottom()");
209 break;
210 default:
211 SkASSERT(false);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400212 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500213 } else if (type.kind() == Type::kEnum_Kind) {
214 this->write("%d");
215 fFormatArgs.push_back("(int) " + cppCode);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400216 } else if (type == *fContext.fInt4_Type ||
217 type == *fContext.fShort4_Type ||
218 type == *fContext.fByte4_Type) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500219 this->write(type.name() + "(%d, %d, %d, %d)");
220 fFormatArgs.push_back(cppCode + ".left()");
221 fFormatArgs.push_back(cppCode + ".top()");
222 fFormatArgs.push_back(cppCode + ".right()");
223 fFormatArgs.push_back(cppCode + ".bottom()");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400224 } else {
Ethan Nicholas82399462017-10-16 12:35:44 -0400225 printf("unsupported runtime value type '%s'\n", String(type.fName).c_str());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400226 SkASSERT(false);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400227 }
228}
229
230void CPPCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
231 if (is_private(var)) {
Ethan Nicholasd608c092017-10-26 09:30:08 -0400232 this->writeRuntimeValue(var.fType, var.fModifiers.fLayout, var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400233 } else {
234 this->writeExpression(value, kTopLevel_Precedence);
235 }
236}
237
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400238String CPPCodeGenerator::getSamplerHandle(const Variable& var) {
239 int samplerCount = 0;
Ethan Nicholas68990be2017-07-13 09:36:52 -0400240 for (const auto param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400241 if (&var == param) {
242 return "args.fTexSamplers[" + to_string(samplerCount) + "]";
243 }
244 if (param->fType.kind() == Type::kSampler_Kind) {
245 ++samplerCount;
246 }
247 }
248 ABORT("should have found sampler in parameters\n");
249}
250
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400251void CPPCodeGenerator::writeIntLiteral(const IntLiteral& i) {
252 this->write(to_string((int32_t) i.fValue));
253}
254
Ethan Nicholas82399462017-10-16 12:35:44 -0400255void CPPCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
256 if (fCPPMode) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400257 SkASSERT(swizzle.fComponents.size() == 1); // no support for multiple swizzle components yet
Ethan Nicholas82399462017-10-16 12:35:44 -0400258 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
259 switch (swizzle.fComponents[0]) {
260 case 0: this->write(".left()"); break;
261 case 1: this->write(".top()"); break;
262 case 2: this->write(".right()"); break;
263 case 3: this->write(".bottom()"); break;
264 }
265 } else {
266 INHERITED::writeSwizzle(swizzle);
267 }
268}
269
Ethan Nicholas762466e2017-06-29 10:03:38 -0400270void CPPCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400271 if (fCPPMode) {
272 this->write(ref.fVariable.fName);
273 return;
274 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400275 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
276 case SK_INCOLOR_BUILTIN:
277 this->write("%s");
Michael Ludwig231de032018-08-30 14:33:01 -0400278 // EmitArgs.fInputColor is automatically set to half4(1) if
279 // no input was specified
280 fFormatArgs.push_back(String("args.fInputColor"));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400281 break;
282 case SK_OUTCOLOR_BUILTIN:
283 this->write("%s");
284 fFormatArgs.push_back(String("args.fOutputColor"));
285 break;
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400286 case SK_MAIN_COORDS_BUILTIN:
287 this->write("%s");
288 fFormatArgs.push_back(String("args.fSampleCoord"));
289 fAccessSampleCoordsDirectly = true;
290 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -0400291 case SK_WIDTH_BUILTIN:
292 this->write("sk_Width");
293 break;
294 case SK_HEIGHT_BUILTIN:
295 this->write("sk_Height");
296 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400297 default:
298 if (ref.fVariable.fType.kind() == Type::kSampler_Kind) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400299 this->write("%s");
300 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerVariable(" +
Stephen Whited523a062019-06-19 13:12:46 -0400301 this->getSamplerHandle(ref.fVariable) + ")");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400302 return;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400303 }
304 if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag) {
305 this->write("%s");
306 String name = ref.fVariable.fName;
Brian Osman1cb41712017-10-19 12:54:52 -0400307 String var = String::printf("args.fUniformHandler->getUniformCStr(%sVar)",
308 HCodeGenerator::FieldName(name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400309 String code;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400310 if (ref.fVariable.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400311 code = String::printf("%sVar.isValid() ? %s : \"%s\"",
312 HCodeGenerator::FieldName(name.c_str()).c_str(),
313 var.c_str(),
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400314 default_value(ref.fVariable.fType).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400315 } else {
316 code = var;
317 }
318 fFormatArgs.push_back(code);
319 } else if (SectionAndParameterHelper::IsParameter(ref.fVariable)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700320 String name(ref.fVariable.fName);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400321 this->writeRuntimeValue(ref.fVariable.fType, ref.fVariable.fModifiers.fLayout,
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400322 String::printf("_outer.%s", name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400323 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700324 this->write(ref.fVariable.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400325 }
326 }
327}
328
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400329void CPPCodeGenerator::writeIfStatement(const IfStatement& s) {
330 if (s.fIsStatic) {
331 this->write("@");
332 }
333 INHERITED::writeIfStatement(s);
334}
335
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400336void CPPCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
337 if (fInMain) {
338 fErrors.error(s.fOffset, "fragmentProcessor main() may not contain return statements");
339 }
340 INHERITED::writeReturnStatement(s);
341}
342
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400343void CPPCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
344 if (s.fIsStatic) {
345 this->write("@");
346 }
347 INHERITED::writeSwitchStatement(s);
348}
349
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400350void CPPCodeGenerator::writeFieldAccess(const FieldAccess& access) {
351 if (access.fBase->fType.name() == "fragmentProcessor") {
352 // Special field access on fragment processors are converted into function calls on
353 // GrFragmentProcessor's getters.
354 if (access.fBase->fKind != Expression::kVariableReference_Kind) {
355 fErrors.error(access.fBase->fOffset, "fragmentProcessor must be a reference\n");
356 return;
357 }
358
359 const Type::Field& field = fContext.fFragmentProcessor_Type->fields()[access.fFieldIndex];
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500360 const Variable& var = ((const VariableReference&) *access.fBase).fVariable;
Brian Osman12c5d292020-07-13 16:11:35 -0400361 String cppAccess = String::printf("_outer.childProcessor(%d)->%s()",
362 this->getChildFPIndex(var),
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500363 String(field.fName).c_str());
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400364
365 if (fCPPMode) {
366 this->write(cppAccess.c_str());
367 } else {
368 writeRuntimeValue(*field.fType, Layout(), cppAccess);
369 }
370 return;
371 }
372 INHERITED::writeFieldAccess(access);
373}
374
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500375int CPPCodeGenerator::getChildFPIndex(const Variable& var) const {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400376 int index = 0;
377 bool found = false;
378 for (const auto& p : fProgram) {
379 if (ProgramElement::kVar_Kind == p.fKind) {
380 const VarDeclarations& decls = (const VarDeclarations&) p;
381 for (const auto& raw : decls.fVars) {
382 const VarDeclaration& decl = (VarDeclaration&) *raw;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500383 if (decl.fVar == &var) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400384 found = true;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500385 } else if (decl.fVar->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400386 ++index;
387 }
388 }
389 }
390 if (found) {
391 break;
392 }
393 }
394 SkASSERT(found);
395 return index;
396}
397
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400398void CPPCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas13863662019-07-29 13:05:15 -0400399 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample" &&
400 c.fArguments[0]->fType.kind() != Type::Kind::kSampler_Kind) {
Leon Scroggins III982fff22020-07-31 14:09:06 -0400401 // Validity checks that are detected by function definition in sksl_fp.inc
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400402 SkASSERT(c.fArguments.size() >= 1 && c.fArguments.size() <= 3);
Florin Malita390f9bd2019-03-04 12:25:57 -0500403 SkASSERT("fragmentProcessor" == c.fArguments[0]->fType.name() ||
404 "fragmentProcessor?" == c.fArguments[0]->fType.name());
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400405
406 // Actually fail during compilation if arguments with valid types are
Ethan Nicholas13863662019-07-29 13:05:15 -0400407 // provided that are not variable references, since sample() is a
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400408 // special function that impacts code emission.
409 if (c.fArguments[0]->fKind != Expression::kVariableReference_Kind) {
410 fErrors.error(c.fArguments[0]->fOffset,
Ethan Nicholas13863662019-07-29 13:05:15 -0400411 "sample()'s fragmentProcessor argument must be a variable reference\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400412 return;
413 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500414 const Variable& child = ((const VariableReference&) *c.fArguments[0]).fVariable;
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400415
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400416 // Start a new extra emit code section so that the emitted child processor can depend on
417 // sksl variables defined in earlier sksl code.
418 this->newExtraEmitCodeBlock();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400419
Michael Ludwige88320b2020-06-24 09:04:56 -0400420 String inputColor;
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400421 if (c.fArguments.size() > 1 && c.fArguments[1]->fType.name() == "half4") {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400422 // Use the invokeChild() variant that accepts an input color, so convert the 2nd
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400423 // argument's expression into C++ code that produces sksl stored in an SkString.
Brian Osman12c5d292020-07-13 16:11:35 -0400424 String inputColorName = "_input" + to_string(c.fOffset);
John Stilesd060c9d2020-06-08 11:44:25 -0400425 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments[1], inputColorName));
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400426
Michael Ludwige88320b2020-06-24 09:04:56 -0400427 // invokeChild() needs a char* and a pre-pended comma
428 inputColor = ", " + inputColorName + ".c_str()";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400429 }
430
Michael Ludwige88320b2020-06-24 09:04:56 -0400431 String inputCoord;
432 String invokeFunction = "invokeChild";
433 if (c.fArguments.back()->fType.name() == "float2") {
434 // Invoking child with explicit coordinates at this call site
435 inputCoord = "_coords" + to_string(c.fOffset);
436 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), inputCoord));
437 inputCoord.append(".c_str()");
438 } else if (c.fArguments.back()->fType.name() == "float3x3") {
439 // Invoking child with a matrix, sampling relative to the input coords.
440 invokeFunction = "invokeChildWithMatrix";
Brian Osman1298bc42020-06-30 13:39:35 -0400441 SampleUsage usage = Analysis::GetSampleUsage(fProgram, child);
Michael Ludwige88320b2020-06-24 09:04:56 -0400442
Brian Osman1298bc42020-06-30 13:39:35 -0400443 if (!usage.hasUniformMatrix()) {
Michael Ludwige88320b2020-06-24 09:04:56 -0400444 inputCoord = "_matrix" + to_string(c.fOffset);
445 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), inputCoord));
446 inputCoord.append(".c_str()");
447 }
448 // else pass in the empty string to rely on invokeChildWithMatrix's automatic uniform
449 // resolution
450 }
451 if (!inputCoord.empty()) {
452 inputCoord = ", " + inputCoord;
453 }
454
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400455 // Write the output handling after the possible input handling
Ethan Nicholas13863662019-07-29 13:05:15 -0400456 String childName = "_sample" + to_string(c.fOffset);
Brian Osman12c5d292020-07-13 16:11:35 -0400457 String childIndexStr = to_string(this->getChildFPIndex(child));
458 addExtraEmitCodeLine("SkString " + childName + " = this->" + invokeFunction + "(" +
459 childIndexStr + inputColor + ", args" + inputCoord + ");");
John Stiles50819422020-06-18 13:00:38 -0400460
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000461 this->write("%s");
462 fFormatArgs.push_back(childName + ".c_str()");
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400463 return;
464 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400465 if (c.fFunction.fBuiltin) {
466 INHERITED::writeFunctionCall(c);
467 } else {
468 this->write("%s");
469 fFormatArgs.push_back((String(c.fFunction.fName) + "_name.c_str()").c_str());
470 this->write("(");
471 const char* separator = "";
472 for (const auto& arg : c.fArguments) {
473 this->write(separator);
474 separator = ", ";
475 this->writeExpression(*arg, kSequence_Precedence);
476 }
477 this->write(")");
478 }
Ethan Nicholas13863662019-07-29 13:05:15 -0400479 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample") {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400480 this->write(".%s");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400481 SkASSERT(c.fArguments.size() >= 1);
482 SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400483 String sampler = this->getSamplerHandle(((VariableReference&) *c.fArguments[0]).fVariable);
484 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
Greg Daniel369ee6b2019-12-02 15:30:02 -0500485 ").asString().c_str()");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400486 }
487}
488
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400489static const char* glsltype_string(const Context& context, const Type& type) {
490 if (type == *context.fFloat_Type) {
491 return "kFloat_GrSLType";
492 } else if (type == *context.fHalf_Type) {
493 return "kHalf_GrSLType";
494 } else if (type == *context.fFloat2_Type) {
495 return "kFloat2_GrSLType";
496 } else if (type == *context.fHalf2_Type) {
497 return "kHalf2_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500498 } else if (type == *context.fFloat3_Type) {
499 return "kFloat3_GrSLType";
500 } else if (type == *context.fHalf3_Type) {
501 return "kHalf3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400502 } else if (type == *context.fFloat4_Type) {
503 return "kFloat4_GrSLType";
504 } else if (type == *context.fHalf4_Type) {
505 return "kHalf4_GrSLType";
Ethan Nicholas58430122020-04-14 09:54:02 -0400506 } else if (type == *context.fFloat2x2_Type) {
507 return "kFloat2x2_GrSLType";
508 } else if (type == *context.fHalf2x2_Type) {
509 return "kHalf2x2_GrSLType";
510 } else if (type == *context.fFloat3x3_Type) {
511 return "kFloat3x3_GrSLType";
512 } else if (type == *context.fHalf3x3_Type) {
513 return "kHalf3x3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400514 } else if (type == *context.fFloat4x4_Type) {
515 return "kFloat4x4_GrSLType";
516 } else if (type == *context.fHalf4x4_Type) {
517 return "kHalf4x4_GrSLType";
518 } else if (type == *context.fVoid_Type) {
519 return "kVoid_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500520 } else if (type.kind() == Type::kEnum_Kind) {
521 return "int";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400522 }
523 SkASSERT(false);
524 return nullptr;
525}
526
Ethan Nicholas762466e2017-06-29 10:03:38 -0400527void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400528 const FunctionDeclaration& decl = f.fDeclaration;
Brian Osman08f986d2020-05-13 17:06:46 -0400529 if (decl.fBuiltin) {
530 return;
531 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400532 fFunctionHeader = "";
533 OutputStream* oldOut = fOut;
534 StringStream buffer;
535 fOut = &buffer;
536 if (decl.fName == "main") {
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400537 fInMain = true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400538 for (const auto& s : ((Block&) *f.fBody).fStatements) {
539 this->writeStatement(*s);
540 this->writeLine();
541 }
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400542 fInMain = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400543
544 fOut = oldOut;
545 this->write(fFunctionHeader);
546 this->write(buffer.str());
547 } else {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400548 this->addExtraEmitCodeLine("SkString " + decl.fName + "_name;");
549 String args = "const GrShaderVar " + decl.fName + "_args[] = { ";
550 const char* separator = "";
551 for (const auto& param : decl.fParameters) {
552 args += String(separator) + "GrShaderVar(\"" + param->fName + "\", " +
553 glsltype_string(fContext, param->fType) + ")";
554 separator = ", ";
555 }
556 args += "};";
557 this->addExtraEmitCodeLine(args.c_str());
558 for (const auto& s : ((Block&) *f.fBody).fStatements) {
559 this->writeStatement(*s);
560 this->writeLine();
561 }
562
563 fOut = oldOut;
564 String emit = "fragBuilder->emitFunction(";
565 emit += glsltype_string(fContext, decl.fReturnType);
566 emit += ", \"" + decl.fName + "\"";
567 emit += ", " + to_string((int64_t) decl.fParameters.size());
568 emit += ", " + decl.fName + "_args";
John Stiles50819422020-06-18 13:00:38 -0400569 emit += ",\nR\"SkSL(" + buffer.str() + ")SkSL\"";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400570 emit += ", &" + decl.fName + "_name);";
571 this->addExtraEmitCodeLine(emit.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400572 }
573}
574
575void CPPCodeGenerator::writeSetting(const Setting& s) {
Brian Osmanf265afd2020-08-04 13:23:36 -0400576 this->write(s.fName.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400577}
578
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400579bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400580 const Section* s = fSectionAndParameterHelper.getSection(name);
581 if (s) {
582 this->writef("%s%s", prefix, s->fText.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400583 return true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400584 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400585 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400586}
587
588void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
589 if (p.fKind == ProgramElement::kSection_Kind) {
590 return;
591 }
592 if (p.fKind == ProgramElement::kVar_Kind) {
593 const VarDeclarations& decls = (const VarDeclarations&) p;
594 if (!decls.fVars.size()) {
595 return;
596 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000597 const Variable& var = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400598 if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
599 -1 != var.fModifiers.fLayout.fBuiltin) {
600 return;
601 }
602 }
603 INHERITED::writeProgramElement(p);
604}
605
606void CPPCodeGenerator::addUniform(const Variable& var) {
607 if (!needs_uniform_var(var)) {
608 return;
609 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400610 if (var.fModifiers.fLayout.fWhen.fLength) {
611 this->writef(" if (%s) {\n ", String(var.fModifiers.fLayout.fWhen).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400612 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400613 const char* type = glsltype_string(fContext, var.fType);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700614 String name(var.fName);
Ethan Nicholas16464c32020-04-06 13:53:05 -0400615 this->writef(" %sVar = args.fUniformHandler->addUniform(&_outer, kFragment_GrShaderFlag,"
616 " %s, \"%s\");\n", HCodeGenerator::FieldName(name.c_str()).c_str(), type,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700617 name.c_str());
Ethan Nicholasfc994162019-06-06 10:04:27 -0400618 if (var.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400619 this->write(" }\n");
620 }
621}
622
Ethan Nicholascd700e92018-08-24 16:43:57 -0400623void CPPCodeGenerator::writeInputVars() {
624}
625
Ethan Nicholas762466e2017-06-29 10:03:38 -0400626void CPPCodeGenerator::writePrivateVars() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400627 for (const auto& p : fProgram) {
628 if (ProgramElement::kVar_Kind == p.fKind) {
629 const VarDeclarations& decls = (const VarDeclarations&) p;
630 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000631 VarDeclaration& decl = (VarDeclaration&) *raw;
632 if (is_private(*decl.fVar)) {
633 if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
634 fErrors.error(decl.fOffset,
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400635 "fragmentProcessor variables must be declared 'in'");
636 return;
637 }
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500638 this->writef("%s %s = %s;\n",
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000639 HCodeGenerator::FieldType(fContext, decl.fVar->fType,
640 decl.fVar->fModifiers.fLayout).c_str(),
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500641 String(decl.fVar->fName).c_str(),
642 default_value(*decl.fVar).c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400643 } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
644 // An auto-tracked uniform in variable, so add a field to hold onto the prior
645 // state. Note that tracked variables must be uniform in's and that is validated
646 // before writePrivateVars() is called.
647 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
648 SkASSERT(mapper && mapper->supportsTracking());
649
650 String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
651 // The member statement is different if the mapper reports a default value
652 if (mapper->defaultValue().size() > 0) {
653 this->writef("%s %sPrev = %s;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400654 Layout::CTypeToStr(mapper->ctype()), name.c_str(),
Michael Ludwiga4275592018-08-31 10:52:47 -0400655 mapper->defaultValue().c_str());
656 } else {
657 this->writef("%s %sPrev;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400658 Layout::CTypeToStr(mapper->ctype()), name.c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400659 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400660 }
661 }
662 }
663 }
664}
665
666void CPPCodeGenerator::writePrivateVarValues() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400667 for (const auto& p : fProgram) {
668 if (ProgramElement::kVar_Kind == p.fKind) {
669 const VarDeclarations& decls = (const VarDeclarations&) p;
670 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000671 VarDeclaration& decl = (VarDeclaration&) *raw;
672 if (is_private(*decl.fVar) && decl.fValue) {
673 this->writef("%s = ", String(decl.fVar->fName).c_str());
Ethan Nicholas82399462017-10-16 12:35:44 -0400674 fCPPMode = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000675 this->writeExpression(*decl.fValue, kAssignment_Precedence);
Ethan Nicholas82399462017-10-16 12:35:44 -0400676 fCPPMode = false;
677 this->write(";\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400678 }
679 }
680 }
681 }
682}
683
Ethan Nicholas82399462017-10-16 12:35:44 -0400684static bool is_accessible(const Variable& var) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500685 const Type& type = var.fType.nonnullable();
686 return Type::kSampler_Kind != type.kind() &&
687 Type::kOther_Kind != type.kind();
Ethan Nicholas82399462017-10-16 12:35:44 -0400688}
689
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400690void CPPCodeGenerator::newExtraEmitCodeBlock() {
691 // This should only be called when emitting SKSL for emitCode(), which can be detected if the
692 // cpp buffer is not null, and the cpp buffer is not the current output.
693 SkASSERT(fCPPBuffer && fCPPBuffer != fOut);
694
695 // Start a new block as an empty string
696 fExtraEmitCodeBlocks.push_back("");
697 // Mark its location in the output buffer, uses ${\d} for the token since ${} will not occur in
698 // valid sksl and makes detection trivial.
699 this->writef("${%zu}", fExtraEmitCodeBlocks.size() - 1);
700}
701
702void CPPCodeGenerator::addExtraEmitCodeLine(const String& toAppend) {
703 SkASSERT(fExtraEmitCodeBlocks.size() > 0);
704 String& currentBlock = fExtraEmitCodeBlocks[fExtraEmitCodeBlocks.size() - 1];
705 // Automatically add indentation and newline
706 currentBlock += " " + toAppend + "\n";
707}
708
709void CPPCodeGenerator::flushEmittedCode() {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400710 if (fCPPBuffer == nullptr) {
711 // Not actually within writeEmitCode() so nothing to flush
712 return;
713 }
714
715 StringStream* skslBuffer = static_cast<StringStream*>(fOut);
716
717 String sksl = skslBuffer->str();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400718 // Empty the accumulation buffer since its current contents are consumed.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400719 skslBuffer->reset();
720
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400721 // Switch to the cpp buffer
Michael Ludwigd0440192018-09-07 14:24:52 +0000722 fOut = fCPPBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400723
724 // Iterate through the sksl, keeping track of where the last statement ended (e.g. the latest
725 // encountered ';', '{', or '}'). If an extra emit code block token is encountered then the
726 // code from 0 to last statement end is sent to writeCodeAppend, the extra code block is
727 // appended to the cpp buffer, and then the sksl string is trimmed to start where the last
728 // statement left off (minus the encountered token).
729 size_t i = 0;
730 int flushPoint = -1;
731 int tokenStart = -1;
732 while (i < sksl.size()) {
733 if (tokenStart >= 0) {
734 // Looking for the end of the token
735 if (sksl[i] == '}') {
736 // Must append the sksl from 0 to flushPoint (inclusive) then the extra code
737 // accumulated in the block with index parsed from chars [tokenStart+2, i-1]
738 String toFlush = String(sksl.c_str(), flushPoint + 1);
739 // writeCodeAppend automatically removes the format args that it consumed, so
740 // fFormatArgs will be in a valid state for any future sksl
741 this->writeCodeAppend(toFlush);
742
743 int codeBlock = stoi(String(sksl.c_str() + tokenStart + 2, i - tokenStart - 2));
744 SkASSERT(codeBlock < (int) fExtraEmitCodeBlocks.size());
745 if (fExtraEmitCodeBlocks[codeBlock].size() > 0) {
746 this->write(fExtraEmitCodeBlocks[codeBlock].c_str());
747 }
748
749 // Now reset the sksl buffer to start after the flush point, but remove the token.
750 String compacted = String(sksl.c_str() + flushPoint + 1,
751 tokenStart - flushPoint - 1);
752 if (i < sksl.size() - 1) {
753 compacted += String(sksl.c_str() + i + 1, sksl.size() - i - 1);
754 }
755 sksl = compacted;
756
757 // And reset iteration
758 i = -1;
759 flushPoint = -1;
760 tokenStart = -1;
761 }
762 } else {
763 // Looking for the start of extra emit block tokens, and tracking when statements end
764 if (sksl[i] == ';' || sksl[i] == '{' || sksl[i] == '}') {
765 flushPoint = i;
766 } else if (i < sksl.size() - 1 && sksl[i] == '$' && sksl[i + 1] == '{') {
767 // found an extra emit code block token
768 tokenStart = i++;
769 }
770 }
771 i++;
Michael Ludwigd0440192018-09-07 14:24:52 +0000772 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400773
774 // Once we've gone through the sksl string to this point, there are no remaining extra emit
775 // code blocks to interleave, so append the remainder as usual.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400776 this->writeCodeAppend(sksl);
777
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400778 // After appending, switch back to the emptied sksl buffer and reset the extra code blocks
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400779 fOut = skslBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400780 fExtraEmitCodeBlocks.clear();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400781}
782
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400783void CPPCodeGenerator::writeCodeAppend(const String& code) {
John Stiles50819422020-06-18 13:00:38 -0400784 if (!code.empty()) {
785 // Count % format specifiers.
786 size_t argCount = 0;
787 for (size_t index = 0; index < code.size(); ++index) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400788 if ('%' == code[index]) {
John Stiles50819422020-06-18 13:00:38 -0400789 if (index == code.size() - 1) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400790 break;
791 }
792 if (code[index + 1] != '%') {
793 ++argCount;
794 }
795 }
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400796 }
John Stiles50819422020-06-18 13:00:38 -0400797
798 // Emit the code string.
799 this->writef(" fragBuilder->codeAppendf(\n"
800 "R\"SkSL(%s)SkSL\"\n", code.c_str());
801 for (size_t i = 0; i < argCount; ++i) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400802 this->writef(", %s", fFormatArgs[i].c_str());
803 }
804 this->write(");\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400805
John Stiles50819422020-06-18 13:00:38 -0400806 // argCount is equal to the number of fFormatArgs that were consumed, so they should be
807 // removed from the list.
808 if (argCount > 0) {
809 fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argCount);
810 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400811 }
812}
813
814String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
815 const String& cppVar) {
816 // To do this conversion, we temporarily switch the sksl output stream
817 // to an empty stringstream and reset the format args to empty.
818 OutputStream* oldSKSL = fOut;
819 StringStream exprBuffer;
820 fOut = &exprBuffer;
821
822 std::vector<String> oldArgs(fFormatArgs);
823 fFormatArgs.clear();
824
825 // Convert the argument expression into a format string and args
826 this->writeExpression(e, Precedence::kTopLevel_Precedence);
827 std::vector<String> newArgs(fFormatArgs);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400828 String expr = exprBuffer.str();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400829
830 // After generating, restore the original output stream and format args
831 fFormatArgs = oldArgs;
832 fOut = oldSKSL;
833
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400834 // The sksl written to exprBuffer is not processed by flushEmittedCode(), so any extra emit code
835 // block tokens won't get handled. So we need to strip them from the expression and stick them
836 // to the end of the original sksl stream.
837 String exprFormat = "";
838 int tokenStart = -1;
839 for (size_t i = 0; i < expr.size(); i++) {
840 if (tokenStart >= 0) {
841 if (expr[i] == '}') {
842 // End of the token, so append the token to fOut
843 fOut->write(expr.c_str() + tokenStart, i - tokenStart + 1);
844 tokenStart = -1;
845 }
846 } else {
847 if (i < expr.size() - 1 && expr[i] == '$' && expr[i + 1] == '{') {
848 tokenStart = i++;
849 } else {
850 exprFormat += expr[i];
851 }
852 }
853 }
854
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400855 // Now build the final C++ code snippet from the format string and args
856 String cppExpr;
John Stiles50819422020-06-18 13:00:38 -0400857 if (newArgs.empty()) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400858 // This was a static expression, so we can simplify the input
859 // color declaration in the emitted code to just a static string
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400860 cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");";
John Stiles50819422020-06-18 13:00:38 -0400861 } else if (newArgs.size() == 1 && exprFormat == "%s") {
862 // If the format expression is simply "%s", we can avoid an expensive call to printf.
863 // This happens fairly often in codegen so it is worth simplifying.
864 cppExpr = "SkString " + cppVar + "(" + newArgs[0] + ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400865 } else {
866 // String formatting must occur dynamically, so have the C++ declaration
867 // use SkStringPrintf with the format args that were accumulated
868 // when the expression was written.
869 cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
870 for (size_t i = 0; i < newArgs.size(); i++) {
871 cppExpr += ", " + newArgs[i];
872 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400873 cppExpr += ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400874 }
875 return cppExpr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400876}
877
Ethan Nicholas762466e2017-06-29 10:03:38 -0400878bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
879 this->write(" void emitCode(EmitArgs& args) override {\n"
880 " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
881 this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
882 " (void) _outer;\n",
883 fFullName.c_str(), fFullName.c_str());
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400884 for (const auto& p : fProgram) {
885 if (ProgramElement::kVar_Kind == p.fKind) {
886 const VarDeclarations& decls = (const VarDeclarations&) p;
887 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000888 VarDeclaration& decl = (VarDeclaration&) *raw;
889 String nameString(decl.fVar->fName);
Ethan Nicholas82399462017-10-16 12:35:44 -0400890 const char* name = nameString.c_str();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000891 if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
892 is_accessible(*decl.fVar)) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400893 this->writef(" auto %s = _outer.%s;\n"
Ethan Nicholas82399462017-10-16 12:35:44 -0400894 " (void) %s;\n",
895 name, name, name);
896 }
897 }
898 }
899 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400900 this->writePrivateVarValues();
901 for (const auto u : uniforms) {
902 this->addUniform(*u);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400903 }
904 this->writeSection(EMIT_CODE_SECTION);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400905
906 // Save original buffer as the CPP buffer for flushEmittedCode()
907 fCPPBuffer = fOut;
908 StringStream skslBuffer;
909 fOut = &skslBuffer;
910
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400911 this->newExtraEmitCodeBlock();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400912 bool result = INHERITED::generateCode();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400913 this->flushEmittedCode();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400914
915 // Then restore the original CPP buffer and close the function
916 fOut = fCPPBuffer;
917 fCPPBuffer = nullptr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400918 this->write(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400919 return result;
920}
921
922void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
923 const char* fullName = fFullName.c_str();
Ethan Nicholas68990be2017-07-13 09:36:52 -0400924 const Section* section = fSectionAndParameterHelper.getSection(SET_DATA_SECTION);
925 const char* pdman = section ? section->fArgument.c_str() : "pdman";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400926 this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
927 "const GrFragmentProcessor& _proc) override {\n",
928 pdman);
929 bool wroteProcessor = false;
John Stiles06f3d082020-06-04 11:07:21 -0400930 for (const Variable* u : uniforms) {
Michael Ludwiga4275592018-08-31 10:52:47 -0400931 if (is_uniform_in(*u)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400932 if (!wroteProcessor) {
933 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
934 wroteProcessor = true;
935 this->writef(" {\n");
936 }
Michael Ludwiga4275592018-08-31 10:52:47 -0400937
938 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
939 SkASSERT(mapper);
940
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700941 String nameString(u->fName);
942 const char* name = nameString.c_str();
Michael Ludwiga4275592018-08-31 10:52:47 -0400943
944 // Switches for setData behavior in the generated code
945 bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
946 bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
947 bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
948
949 String uniformName = HCodeGenerator::FieldName(name) + "Var";
950
951 String indent = " "; // 8 by default, 12 when nested for conditional uniforms
952 if (conditionalUniform) {
953 // Add a pre-check to make sure the uniform was emitted
954 // before trying to send any data to the GPU
955 this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
956 indent += " ";
957 }
958
959 String valueVar = "";
960 if (needsValueDeclaration) {
961 valueVar.appendf("%sValue", name);
962 // Use AccessType since that will match the return type of _outer's public API.
963 String valueType = HCodeGenerator::AccessType(fContext, u->fType,
964 u->fModifiers.fLayout);
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400965 this->writef("%s%s %s = _outer.%s;\n",
Michael Ludwiga4275592018-08-31 10:52:47 -0400966 indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400967 } else {
Michael Ludwiga4275592018-08-31 10:52:47 -0400968 // Not tracked and the mapper only needs to use the value once
969 // so send it a safe expression instead of the variable name
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400970 valueVar.appendf("(_outer.%s)", name);
Michael Ludwiga4275592018-08-31 10:52:47 -0400971 }
972
973 if (isTracked) {
974 SkASSERT(mapper->supportsTracking());
975
976 String prevVar = HCodeGenerator::FieldName(name) + "Prev";
977 this->writef("%sif (%s) {\n"
978 "%s %s;\n"
979 "%s %s;\n"
980 "%s}\n", indent.c_str(),
981 mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
982 mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
983 mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
984 } else {
985 this->writef("%s%s;\n", indent.c_str(),
986 mapper->setUniform(pdman, uniformName, valueVar).c_str());
987 }
988
989 if (conditionalUniform) {
990 // Close the earlier precheck block
991 this->writef(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400992 }
993 }
994 }
995 if (wroteProcessor) {
996 this->writef(" }\n");
997 }
Ethan Nicholas68990be2017-07-13 09:36:52 -0400998 if (section) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500999 int samplerIndex = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001000 for (const auto& p : fProgram) {
1001 if (ProgramElement::kVar_Kind == p.fKind) {
1002 const VarDeclarations& decls = (const VarDeclarations&) p;
John Stiles06f3d082020-06-04 11:07:21 -04001003 for (const std::unique_ptr<Statement>& raw : decls.fVars) {
1004 const VarDeclaration& decl = static_cast<VarDeclaration&>(*raw);
1005 const Variable& variable = *decl.fVar;
1006 String nameString(variable.fName);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001007 const char* name = nameString.c_str();
John Stiles06f3d082020-06-04 11:07:21 -04001008 if (variable.fType.kind() == Type::kSampler_Kind) {
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001009 this->writef(" const GrSurfaceProxyView& %sView = "
1010 "_outer.textureSampler(%d).view();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001011 name, samplerIndex);
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001012 this->writef(" GrTexture& %s = *%sView.proxy()->peekTexture();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001013 name, name);
1014 this->writef(" (void) %s;\n", name);
1015 ++samplerIndex;
John Stiles06f3d082020-06-04 11:07:21 -04001016 } else if (needs_uniform_var(variable)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001017 this->writef(" UniformHandle& %s = %sVar;\n"
1018 " (void) %s;\n",
1019 name, HCodeGenerator::FieldName(name).c_str(), name);
John Stiles06f3d082020-06-04 11:07:21 -04001020 } else if (SectionAndParameterHelper::IsParameter(variable) &&
1021 variable.fType != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001022 if (!wroteProcessor) {
1023 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
1024 fullName);
1025 wroteProcessor = true;
1026 }
John Stiles06f3d082020-06-04 11:07:21 -04001027
1028 if (variable.fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
1029 this->writef(" auto %s = _outer.%s;\n"
1030 " (void) %s;\n",
1031 name, name, name);
1032 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001033 }
1034 }
1035 }
1036 }
1037 this->writeSection(SET_DATA_SECTION);
1038 }
1039 this->write(" }\n");
1040}
1041
Brian Salomonf7dcd762018-07-30 14:48:15 -04001042void CPPCodeGenerator::writeOnTextureSampler() {
1043 bool foundSampler = false;
1044 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1045 if (param->fType.kind() == Type::kSampler_Kind) {
1046 if (!foundSampler) {
1047 this->writef(
1048 "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
1049 "index) const {\n",
1050 fFullName.c_str());
1051 this->writef(" return IthTextureSampler(index, %s",
1052 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1053 foundSampler = true;
1054 } else {
1055 this->writef(", %s",
1056 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1057 }
1058 }
1059 }
1060 if (foundSampler) {
1061 this->write(");\n}\n");
1062 }
1063}
1064
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001065void CPPCodeGenerator::writeClone() {
1066 if (!this->writeSection(CLONE_SECTION)) {
1067 if (fSectionAndParameterHelper.getSection(FIELDS_SECTION)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001068 fErrors.error(0, "fragment processors with custom @fields must also have a custom"
1069 "@clone");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001070 }
1071 this->writef("%s::%s(const %s& src)\n"
Ethan Nicholasabff9562017-10-09 10:54:08 -04001072 ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
1073 fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
John Stiles06f3d082020-06-04 11:07:21 -04001074 for (const Variable* param : fSectionAndParameterHelper.getParameters()) {
Robert Phillipsbce7d862019-02-21 22:53:57 +00001075 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
John Stiles88183902020-06-10 16:40:38 -04001076 if (param->fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001077 this->writef("\n, %s(src.%s)",
1078 fieldName.c_str(),
1079 fieldName.c_str());
1080 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001081 }
Ethan Nicholasabff9562017-10-09 10:54:08 -04001082 this->writef(" {\n");
Brian Osman12c5d292020-07-13 16:11:35 -04001083 this->writef(" this->cloneAndRegisterAllChildProcessors(src);\n");
Brian Salomonf7dcd762018-07-30 14:48:15 -04001084 int samplerCount = 0;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001085 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1086 if (param->fType.kind() == Type::kSampler_Kind) {
Brian Salomonf7dcd762018-07-30 14:48:15 -04001087 ++samplerCount;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001088 }
1089 }
Brian Salomonf7dcd762018-07-30 14:48:15 -04001090 if (samplerCount) {
1091 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
1092 }
Michael Ludwige88320b2020-06-24 09:04:56 -04001093 if (fAccessSampleCoordsDirectly) {
1094 this->writef(" this->setUsesSampleCoordsDirectly();\n");
1095 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001096 this->write("}\n");
Brian Salomonaff329b2017-08-11 09:40:37 -04001097 this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
1098 fFullName.c_str());
John Stilesfbd050b2020-08-03 13:21:46 -04001099 this->writef(" return std::make_unique<%s>(*this);\n",
Brian Salomonaff329b2017-08-11 09:40:37 -04001100 fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001101 this->write("}\n");
1102 }
1103}
1104
Ethan Nicholas762466e2017-06-29 10:03:38 -04001105void CPPCodeGenerator::writeTest() {
Ethan Nicholas68990be2017-07-13 09:36:52 -04001106 const Section* test = fSectionAndParameterHelper.getSection(TEST_CODE_SECTION);
1107 if (test) {
Brian Salomonaff329b2017-08-11 09:40:37 -04001108 this->writef(
1109 "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
1110 "#if GR_TEST_UTILS\n"
1111 "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
1112 fFullName.c_str(),
1113 fFullName.c_str(),
1114 test->fArgument.c_str());
Ethan Nicholas68990be2017-07-13 09:36:52 -04001115 this->writeSection(TEST_CODE_SECTION);
1116 this->write("}\n"
1117 "#endif\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001118 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001119}
1120
1121void CPPCodeGenerator::writeGetKey() {
1122 this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
1123 "GrProcessorKeyBuilder* b) const {\n",
1124 fFullName.c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001125 for (const auto& p : fProgram) {
1126 if (ProgramElement::kVar_Kind == p.fKind) {
1127 const VarDeclarations& decls = (const VarDeclarations&) p;
1128 for (const auto& raw : decls.fVars) {
1129 const VarDeclaration& decl = (VarDeclaration&) *raw;
1130 const Variable& var = *decl.fVar;
1131 String nameString(var.fName);
1132 const char* name = nameString.c_str();
1133 if (var.fModifiers.fLayout.fKey != Layout::kNo_Key &&
1134 (var.fModifiers.fFlags & Modifiers::kUniform_Flag)) {
1135 fErrors.error(var.fOffset,
1136 "layout(key) may not be specified on uniforms");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001137 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001138 switch (var.fModifiers.fLayout.fKey) {
1139 case Layout::kKey_Key:
1140 if (is_private(var)) {
1141 this->writef("%s %s =",
1142 HCodeGenerator::FieldType(fContext, var.fType,
1143 var.fModifiers.fLayout).c_str(),
1144 String(var.fName).c_str());
1145 if (decl.fValue) {
1146 fCPPMode = true;
1147 this->writeExpression(*decl.fValue, kAssignment_Precedence);
1148 fCPPMode = false;
1149 } else {
1150 this->writef("%s", default_value(var).c_str());
1151 }
1152 this->write(";\n");
1153 }
1154 if (var.fModifiers.fLayout.fWhen.fLength) {
1155 this->writef("if (%s) {", String(var.fModifiers.fLayout.fWhen).c_str());
1156 }
John Stilesb3038f82020-07-27 17:33:25 -04001157 if (var.fType == *fContext.fHalf4_Type) {
Ethan Nicholascab767f2019-07-01 13:32:07 -04001158 this->writef(" uint16_t red = SkFloatToHalf(%s.fR);\n",
1159 HCodeGenerator::FieldName(name).c_str());
1160 this->writef(" uint16_t green = SkFloatToHalf(%s.fG);\n",
1161 HCodeGenerator::FieldName(name).c_str());
1162 this->writef(" uint16_t blue = SkFloatToHalf(%s.fB);\n",
1163 HCodeGenerator::FieldName(name).c_str());
1164 this->writef(" uint16_t alpha = SkFloatToHalf(%s.fA);\n",
1165 HCodeGenerator::FieldName(name).c_str());
1166 this->write(" b->add32(((uint32_t)red << 16) | green);\n");
1167 this->write(" b->add32(((uint32_t)blue << 16) | alpha);\n");
John Stiles45f5b032020-07-27 17:31:29 -04001168 } else if (var.fType == *fContext.fHalf_Type ||
1169 var.fType == *fContext.fFloat_Type) {
1170 this->writef(" b->add32(sk_bit_cast<uint32_t>(%s));\n",
Ethan Nicholascab767f2019-07-01 13:32:07 -04001171 HCodeGenerator::FieldName(name).c_str());
John Stiles45f5b032020-07-27 17:31:29 -04001172 } else if (var.fType.isInteger() || var.fType == *fContext.fBool_Type ||
1173 var.fType.kind() == Type::kEnum_Kind) {
1174 this->writef(" b->add32((uint32_t) %s);\n",
1175 HCodeGenerator::FieldName(name).c_str());
1176 } else {
1177 ABORT("NOT YET IMPLEMENTED: automatic key handling for %s\n",
1178 var.fType.displayName().c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001179 }
1180 if (var.fModifiers.fLayout.fWhen.fLength) {
1181 this->write("}");
1182 }
1183 break;
1184 case Layout::kIdentity_Key:
1185 if (var.fType.kind() != Type::kMatrix_Kind) {
1186 fErrors.error(var.fOffset,
1187 "layout(key=identity) requires matrix type");
1188 }
1189 this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
1190 HCodeGenerator::FieldName(name).c_str());
1191 break;
1192 case Layout::kNo_Key:
1193 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001194 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001195 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001196 }
1197 }
1198 this->write("}\n");
1199}
1200
1201bool CPPCodeGenerator::generateCode() {
1202 std::vector<const Variable*> uniforms;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001203 for (const auto& p : fProgram) {
1204 if (ProgramElement::kVar_Kind == p.fKind) {
1205 const VarDeclarations& decls = (const VarDeclarations&) p;
1206 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001207 VarDeclaration& decl = (VarDeclaration&) *raw;
1208 if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1209 decl.fVar->fType.kind() != Type::kSampler_Kind) {
1210 uniforms.push_back(decl.fVar);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001211 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001212
1213 if (is_uniform_in(*decl.fVar)) {
1214 // Validate the "uniform in" declarations to make sure they are fully supported,
1215 // instead of generating surprising C++
1216 const UniformCTypeMapper* mapper =
1217 UniformCTypeMapper::Get(fContext, *decl.fVar);
1218 if (mapper == nullptr) {
1219 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1220 + "'s type is not supported for use as a 'uniform in'");
1221 return false;
1222 }
1223 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1224 if (!mapper->supportsTracking()) {
1225 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1226 + "'s type does not support state tracking");
1227 return false;
1228 }
1229 }
1230
1231 } else {
1232 // If it's not a uniform_in, it's an error to be tracked
1233 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1234 fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
1235 return false;
1236 }
1237 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001238 }
1239 }
1240 }
1241 const char* baseName = fName.c_str();
1242 const char* fullName = fFullName.c_str();
Ethan Nicholas130fb3f2018-02-01 12:14:34 -05001243 this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001244 this->writef(kFragmentProcessorHeader, fullName);
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001245 this->writef("#include \"%s.h\"\n\n", fullName);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001246 this->writeSection(CPP_SECTION);
John Stiles45f5b032020-07-27 17:31:29 -04001247 this->writef("#include \"src/core/SkUtils.h\"\n"
1248 "#include \"src/gpu/GrTexture.h\"\n"
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001249 "#include \"src/gpu/glsl/GrGLSLFragmentProcessor.h\"\n"
1250 "#include \"src/gpu/glsl/GrGLSLFragmentShaderBuilder.h\"\n"
1251 "#include \"src/gpu/glsl/GrGLSLProgramBuilder.h\"\n"
1252 "#include \"src/sksl/SkSLCPP.h\"\n"
1253 "#include \"src/sksl/SkSLUtil.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001254 "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
1255 "public:\n"
1256 " GrGLSL%s() {}\n",
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001257 baseName, baseName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001258 bool result = this->writeEmitCode(uniforms);
1259 this->write("private:\n");
1260 this->writeSetData(uniforms);
1261 this->writePrivateVars();
1262 for (const auto& u : uniforms) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001263 if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001264 this->writef(" UniformHandle %sVar;\n",
1265 HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001266 }
1267 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001268 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001269 if (needs_uniform_var(*param)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001270 this->writef(" UniformHandle %sVar;\n",
1271 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001272 }
1273 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001274 this->writef("};\n"
1275 "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
1276 " return new GrGLSL%s();\n"
1277 "}\n",
1278 fullName, baseName);
1279 this->writeGetKey();
1280 this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
1281 " const %s& that = other.cast<%s>();\n"
1282 " (void) that;\n",
1283 fullName, fullName, fullName);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001284 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001285 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001286 continue;
1287 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001288 String nameString(param->fName);
1289 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001290 this->writef(" if (%s != that.%s) return false;\n",
1291 HCodeGenerator::FieldName(name).c_str(),
1292 HCodeGenerator::FieldName(name).c_str());
1293 }
1294 this->write(" return true;\n"
1295 "}\n");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001296 this->writeClone();
Brian Salomonf7dcd762018-07-30 14:48:15 -04001297 this->writeOnTextureSampler();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001298 this->writeTest();
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001299 this->writeSection(CPP_END_SECTION);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001300
Ethan Nicholas762466e2017-06-29 10:03:38 -04001301 result &= 0 == fErrors.errorCount();
1302 return result;
1303}
1304
John Stilesa6841be2020-08-06 14:11:56 -04001305} // namespace SkSL