blob: 67cbe36ee75d1f1239a1b271b2a68980110752b4 [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) {
John Stiles17c5b702020-08-18 10:40:03 -040087 var = &b.fLeft->as<VariableReference>().fVariable;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050088 } else {
John Stiles17c5b702020-08-18 10:40:03 -040089 var = &b.fRight->as<VariableReference>().fVariable;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050090 }
91 SkASSERT(var->fType.kind() == Type::kNullable_Kind &&
92 var->fType.componentType() == *fContext.fFragmentProcessor_Type);
93 this->write("%s");
Brian Osman12c5d292020-07-13 16:11:35 -040094 const char* op = "";
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050095 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040096 case Token::Kind::TK_EQEQ:
Brian Osman12c5d292020-07-13 16:11:35 -040097 op = "!";
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050098 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040099 case Token::Kind::TK_NEQ:
Brian Osman12c5d292020-07-13 16:11:35 -0400100 op = "";
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500101 break;
102 default:
103 SkASSERT(false);
104 }
Brian Osman12c5d292020-07-13 16:11:35 -0400105 int childIndex = this->getChildFPIndex(*var);
106 fFormatArgs.push_back(String(op) + "_outer.childProcessor(" + to_string(childIndex) +
107 ") ? \"true\" : \"false\"");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400108 } else {
109 INHERITED::writeBinaryExpression(b, parentPrecedence);
110 }
111}
112
113void CPPCodeGenerator::writeIndexExpression(const IndexExpression& i) {
114 const Expression& base = *i.fBase;
115 if (base.fKind == Expression::kVariableReference_Kind) {
John Stiles3dc0da62020-08-19 17:48:31 -0400116 int builtin = base.as<VariableReference>().fVariable.fModifiers.fLayout.fBuiltin;
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400117 if (SK_TEXTURESAMPLERS_BUILTIN == builtin) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400118 this->write("%s");
119 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700120 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400121 "index into sk_TextureSamplers must be an integer literal");
122 return;
123 }
John Stiles81365af2020-08-18 09:24:00 -0400124 int64_t index = i.fIndex->as<IntLiteral>().fValue;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400125 fFormatArgs.push_back(" fragBuilder->getProgramBuilder()->samplerVariable("
Stephen Whited523a062019-06-19 13:12:46 -0400126 "args.fTexSamplers[" + to_string(index) + "])");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400127 return;
128 }
129 }
130 INHERITED::writeIndexExpression(i);
131}
132
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400133static String default_value(const Type& type) {
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500134 if (type.fName == "bool") {
135 return "false";
136 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400137 switch (type.kind()) {
138 case Type::kScalar_Kind: return "0";
139 case Type::kVector_Kind: return type.name() + "(0)";
140 case Type::kMatrix_Kind: return type.name() + "(1)";
141 default: ABORT("unsupported default_value type\n");
142 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400143}
144
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500145static String default_value(const Variable& var) {
Brian Osman495993a2018-10-16 15:45:55 -0400146 if (var.fModifiers.fLayout.fCType == SkSL::Layout::CType::kSkPMColor4f) {
Brian Osmanf28e55d2018-10-03 16:35:54 -0400147 return "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}";
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500148 }
149 return default_value(var.fType);
150}
151
Ethan Nicholas762466e2017-06-29 10:03:38 -0400152static bool is_private(const Variable& var) {
153 return !(var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
154 !(var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
155 var.fStorage == Variable::kGlobal_Storage &&
156 var.fModifiers.fLayout.fBuiltin == -1;
157}
158
Michael Ludwiga4275592018-08-31 10:52:47 -0400159static bool is_uniform_in(const Variable& var) {
160 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
161 (var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
162 var.fType.kind() != Type::kSampler_Kind;
163}
164
John Stiles47b4e222020-08-12 09:56:50 -0400165String CPPCodeGenerator::formatRuntimeValue(const Type& type,
166 const Layout& layout,
167 const String& cppCode,
168 std::vector<String>* formatArgs) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400169 if (type.isFloat()) {
John Stiles47b4e222020-08-12 09:56:50 -0400170 formatArgs->push_back(cppCode);
171 return "%f";
172 }
173 if (type == *fContext.fInt_Type) {
174 formatArgs->push_back(cppCode);
175 return "%d";
176 }
177 if (type == *fContext.fBool_Type) {
178 formatArgs->push_back("(" + cppCode + " ? \"true\" : \"false\")");
179 return "%s";
180 }
181 if (type == *fContext.fFloat2_Type || type == *fContext.fHalf2_Type) {
182 formatArgs->push_back(cppCode + ".fX");
183 formatArgs->push_back(cppCode + ".fY");
184 return type.name() + "(%f, %f)";
185 }
186 if (type == *fContext.fFloat3_Type || type == *fContext.fHalf3_Type) {
187 formatArgs->push_back(cppCode + ".fX");
188 formatArgs->push_back(cppCode + ".fY");
189 formatArgs->push_back(cppCode + ".fZ");
190 return type.name() + "(%f, %f, %f)";
191 }
192 if (type == *fContext.fFloat4_Type || type == *fContext.fHalf4_Type) {
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400193 switch (layout.fCType) {
194 case Layout::CType::kSkPMColor:
John Stiles47b4e222020-08-12 09:56:50 -0400195 formatArgs->push_back("SkGetPackedR32(" + cppCode + ") / 255.0");
196 formatArgs->push_back("SkGetPackedG32(" + cppCode + ") / 255.0");
197 formatArgs->push_back("SkGetPackedB32(" + cppCode + ") / 255.0");
198 formatArgs->push_back("SkGetPackedA32(" + cppCode + ") / 255.0");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400199 break;
Brian Osmanf28e55d2018-10-03 16:35:54 -0400200 case Layout::CType::kSkPMColor4f:
John Stiles47b4e222020-08-12 09:56:50 -0400201 formatArgs->push_back(cppCode + ".fR");
202 formatArgs->push_back(cppCode + ".fG");
203 formatArgs->push_back(cppCode + ".fB");
204 formatArgs->push_back(cppCode + ".fA");
Brian Osmanf28e55d2018-10-03 16:35:54 -0400205 break;
Mike Reedb26b4e72020-01-22 14:31:21 -0500206 case Layout::CType::kSkV4:
John Stiles47b4e222020-08-12 09:56:50 -0400207 formatArgs->push_back(cppCode + ".x");
208 formatArgs->push_back(cppCode + ".y");
209 formatArgs->push_back(cppCode + ".z");
210 formatArgs->push_back(cppCode + ".w");
Brian Salomoneca66b32019-06-01 11:18:15 -0400211 break;
John Stiles47b4e222020-08-12 09:56:50 -0400212 case Layout::CType::kSkRect:
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400213 case Layout::CType::kDefault:
John Stiles47b4e222020-08-12 09:56:50 -0400214 formatArgs->push_back(cppCode + ".left()");
215 formatArgs->push_back(cppCode + ".top()");
216 formatArgs->push_back(cppCode + ".right()");
217 formatArgs->push_back(cppCode + ".bottom()");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400218 break;
219 default:
220 SkASSERT(false);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400221 }
John Stiles47b4e222020-08-12 09:56:50 -0400222 return type.name() + "(%f, %f, %f, %f)";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400223 }
John Stiles47b4e222020-08-12 09:56:50 -0400224 if (type.kind() == Type::kMatrix_Kind) {
225 SkASSERT(type.componentType() == *fContext.fFloat_Type ||
226 type.componentType() == *fContext.fHalf_Type);
227
228 String format = type.name() + "(";
229 for (int c = 0; c < type.columns(); ++c) {
230 for (int r = 0; r < type.rows(); ++r) {
231 formatArgs->push_back(String::printf("%s.rc(%d, %d)", cppCode.c_str(), r, c));
232 format += "%f, ";
233 }
234 }
235
236 // Replace trailing ", " with ")".
237 format.pop_back();
238 format.back() = ')';
239 return format;
240 }
241 if (type.kind() == Type::kEnum_Kind) {
242 formatArgs->push_back("(int) " + cppCode);
243 return "%d";
244 }
245 if (type == *fContext.fInt4_Type ||
246 type == *fContext.fShort4_Type ||
247 type == *fContext.fByte4_Type) {
248 formatArgs->push_back(cppCode + ".left()");
249 formatArgs->push_back(cppCode + ".top()");
250 formatArgs->push_back(cppCode + ".right()");
251 formatArgs->push_back(cppCode + ".bottom()");
252 return type.name() + "(%d, %d, %d, %d)";
253 }
254
255 SkDEBUGFAILF("unsupported runtime value type '%s'\n", String(type.fName).c_str());
256 return "";
257}
258
259void CPPCodeGenerator::writeRuntimeValue(const Type& type, const Layout& layout,
260 const String& cppCode) {
261 this->write(this->formatRuntimeValue(type, layout, cppCode, &fFormatArgs));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400262}
263
264void CPPCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
265 if (is_private(var)) {
Ethan Nicholasd608c092017-10-26 09:30:08 -0400266 this->writeRuntimeValue(var.fType, var.fModifiers.fLayout, var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400267 } else {
268 this->writeExpression(value, kTopLevel_Precedence);
269 }
270}
271
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400272String CPPCodeGenerator::getSamplerHandle(const Variable& var) {
273 int samplerCount = 0;
Ethan Nicholas68990be2017-07-13 09:36:52 -0400274 for (const auto param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400275 if (&var == param) {
276 return "args.fTexSamplers[" + to_string(samplerCount) + "]";
277 }
278 if (param->fType.kind() == Type::kSampler_Kind) {
279 ++samplerCount;
280 }
281 }
282 ABORT("should have found sampler in parameters\n");
283}
284
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400285void CPPCodeGenerator::writeIntLiteral(const IntLiteral& i) {
286 this->write(to_string((int32_t) i.fValue));
287}
288
Ethan Nicholas82399462017-10-16 12:35:44 -0400289void CPPCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
290 if (fCPPMode) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400291 SkASSERT(swizzle.fComponents.size() == 1); // no support for multiple swizzle components yet
Ethan Nicholas82399462017-10-16 12:35:44 -0400292 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
293 switch (swizzle.fComponents[0]) {
294 case 0: this->write(".left()"); break;
295 case 1: this->write(".top()"); break;
296 case 2: this->write(".right()"); break;
297 case 3: this->write(".bottom()"); break;
298 }
299 } else {
300 INHERITED::writeSwizzle(swizzle);
301 }
302}
303
Ethan Nicholas762466e2017-06-29 10:03:38 -0400304void CPPCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400305 if (fCPPMode) {
306 this->write(ref.fVariable.fName);
307 return;
308 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400309 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400310 case SK_OUTCOLOR_BUILTIN:
311 this->write("%s");
312 fFormatArgs.push_back(String("args.fOutputColor"));
313 break;
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400314 case SK_MAIN_COORDS_BUILTIN:
315 this->write("%s");
316 fFormatArgs.push_back(String("args.fSampleCoord"));
317 fAccessSampleCoordsDirectly = true;
318 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -0400319 case SK_WIDTH_BUILTIN:
320 this->write("sk_Width");
321 break;
322 case SK_HEIGHT_BUILTIN:
323 this->write("sk_Height");
324 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400325 default:
326 if (ref.fVariable.fType.kind() == Type::kSampler_Kind) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400327 this->write("%s");
328 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerVariable(" +
Stephen Whited523a062019-06-19 13:12:46 -0400329 this->getSamplerHandle(ref.fVariable) + ")");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400330 return;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400331 }
332 if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag) {
333 this->write("%s");
334 String name = ref.fVariable.fName;
Brian Osman1cb41712017-10-19 12:54:52 -0400335 String var = String::printf("args.fUniformHandler->getUniformCStr(%sVar)",
336 HCodeGenerator::FieldName(name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400337 String code;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400338 if (ref.fVariable.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400339 code = String::printf("%sVar.isValid() ? %s : \"%s\"",
340 HCodeGenerator::FieldName(name.c_str()).c_str(),
341 var.c_str(),
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400342 default_value(ref.fVariable.fType).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400343 } else {
344 code = var;
345 }
346 fFormatArgs.push_back(code);
347 } else if (SectionAndParameterHelper::IsParameter(ref.fVariable)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700348 String name(ref.fVariable.fName);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400349 this->writeRuntimeValue(ref.fVariable.fType, ref.fVariable.fModifiers.fLayout,
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400350 String::printf("_outer.%s", name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400351 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700352 this->write(ref.fVariable.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400353 }
354 }
355}
356
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400357void CPPCodeGenerator::writeIfStatement(const IfStatement& s) {
358 if (s.fIsStatic) {
359 this->write("@");
360 }
361 INHERITED::writeIfStatement(s);
362}
363
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400364void CPPCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
365 if (fInMain) {
366 fErrors.error(s.fOffset, "fragmentProcessor main() may not contain return statements");
367 }
368 INHERITED::writeReturnStatement(s);
369}
370
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400371void CPPCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
372 if (s.fIsStatic) {
373 this->write("@");
374 }
375 INHERITED::writeSwitchStatement(s);
376}
377
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400378void CPPCodeGenerator::writeFieldAccess(const FieldAccess& access) {
379 if (access.fBase->fType.name() == "fragmentProcessor") {
380 // Special field access on fragment processors are converted into function calls on
381 // GrFragmentProcessor's getters.
382 if (access.fBase->fKind != Expression::kVariableReference_Kind) {
383 fErrors.error(access.fBase->fOffset, "fragmentProcessor must be a reference\n");
384 return;
385 }
386
387 const Type::Field& field = fContext.fFragmentProcessor_Type->fields()[access.fFieldIndex];
John Stiles3dc0da62020-08-19 17:48:31 -0400388 const Variable& var = access.fBase->as<VariableReference>().fVariable;
Brian Osman12c5d292020-07-13 16:11:35 -0400389 String cppAccess = String::printf("_outer.childProcessor(%d)->%s()",
390 this->getChildFPIndex(var),
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500391 String(field.fName).c_str());
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400392
393 if (fCPPMode) {
394 this->write(cppAccess.c_str());
395 } else {
396 writeRuntimeValue(*field.fType, Layout(), cppAccess);
397 }
398 return;
399 }
400 INHERITED::writeFieldAccess(access);
401}
402
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500403int CPPCodeGenerator::getChildFPIndex(const Variable& var) const {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400404 int index = 0;
405 bool found = false;
406 for (const auto& p : fProgram) {
407 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -0400408 const VarDeclarations& decls = p.as<VarDeclarations>();
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400409 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -0400410 const VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500411 if (decl.fVar == &var) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400412 found = true;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500413 } else if (decl.fVar->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400414 ++index;
415 }
416 }
417 }
418 if (found) {
419 break;
420 }
421 }
422 SkASSERT(found);
423 return index;
424}
425
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400426void CPPCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas13863662019-07-29 13:05:15 -0400427 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample" &&
428 c.fArguments[0]->fType.kind() != Type::Kind::kSampler_Kind) {
Leon Scroggins III982fff22020-07-31 14:09:06 -0400429 // Validity checks that are detected by function definition in sksl_fp.inc
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400430 SkASSERT(c.fArguments.size() >= 1 && c.fArguments.size() <= 3);
Florin Malita390f9bd2019-03-04 12:25:57 -0500431 SkASSERT("fragmentProcessor" == c.fArguments[0]->fType.name() ||
432 "fragmentProcessor?" == c.fArguments[0]->fType.name());
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400433
434 // Actually fail during compilation if arguments with valid types are
Ethan Nicholas13863662019-07-29 13:05:15 -0400435 // provided that are not variable references, since sample() is a
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400436 // special function that impacts code emission.
437 if (c.fArguments[0]->fKind != Expression::kVariableReference_Kind) {
438 fErrors.error(c.fArguments[0]->fOffset,
Ethan Nicholas13863662019-07-29 13:05:15 -0400439 "sample()'s fragmentProcessor argument must be a variable reference\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400440 return;
441 }
John Stiles3dc0da62020-08-19 17:48:31 -0400442 const Variable& child = c.fArguments[0]->as<VariableReference>().fVariable;
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400443
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400444 // Start a new extra emit code section so that the emitted child processor can depend on
445 // sksl variables defined in earlier sksl code.
446 this->newExtraEmitCodeBlock();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400447
Michael Ludwige88320b2020-06-24 09:04:56 -0400448 String inputColor;
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400449 if (c.fArguments.size() > 1 && c.fArguments[1]->fType.name() == "half4") {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400450 // Use the invokeChild() variant that accepts an input color, so convert the 2nd
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400451 // argument's expression into C++ code that produces sksl stored in an SkString.
Brian Osman12c5d292020-07-13 16:11:35 -0400452 String inputColorName = "_input" + to_string(c.fOffset);
John Stilesd060c9d2020-06-08 11:44:25 -0400453 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments[1], inputColorName));
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400454
Michael Ludwige88320b2020-06-24 09:04:56 -0400455 // invokeChild() needs a char* and a pre-pended comma
456 inputColor = ", " + inputColorName + ".c_str()";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400457 }
458
Michael Ludwige88320b2020-06-24 09:04:56 -0400459 String inputCoord;
460 String invokeFunction = "invokeChild";
461 if (c.fArguments.back()->fType.name() == "float2") {
462 // Invoking child with explicit coordinates at this call site
463 inputCoord = "_coords" + to_string(c.fOffset);
464 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), inputCoord));
465 inputCoord.append(".c_str()");
466 } else if (c.fArguments.back()->fType.name() == "float3x3") {
467 // Invoking child with a matrix, sampling relative to the input coords.
468 invokeFunction = "invokeChildWithMatrix";
Brian Osman1298bc42020-06-30 13:39:35 -0400469 SampleUsage usage = Analysis::GetSampleUsage(fProgram, child);
Michael Ludwige88320b2020-06-24 09:04:56 -0400470
Brian Osman1298bc42020-06-30 13:39:35 -0400471 if (!usage.hasUniformMatrix()) {
Michael Ludwige88320b2020-06-24 09:04:56 -0400472 inputCoord = "_matrix" + to_string(c.fOffset);
473 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), inputCoord));
474 inputCoord.append(".c_str()");
475 }
476 // else pass in the empty string to rely on invokeChildWithMatrix's automatic uniform
477 // resolution
478 }
479 if (!inputCoord.empty()) {
480 inputCoord = ", " + inputCoord;
481 }
482
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400483 // Write the output handling after the possible input handling
Ethan Nicholas13863662019-07-29 13:05:15 -0400484 String childName = "_sample" + to_string(c.fOffset);
Brian Osman12c5d292020-07-13 16:11:35 -0400485 String childIndexStr = to_string(this->getChildFPIndex(child));
486 addExtraEmitCodeLine("SkString " + childName + " = this->" + invokeFunction + "(" +
487 childIndexStr + inputColor + ", args" + inputCoord + ");");
John Stiles50819422020-06-18 13:00:38 -0400488
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000489 this->write("%s");
490 fFormatArgs.push_back(childName + ".c_str()");
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400491 return;
492 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400493 if (c.fFunction.fBuiltin) {
494 INHERITED::writeFunctionCall(c);
495 } else {
496 this->write("%s");
497 fFormatArgs.push_back((String(c.fFunction.fName) + "_name.c_str()").c_str());
498 this->write("(");
499 const char* separator = "";
500 for (const auto& arg : c.fArguments) {
501 this->write(separator);
502 separator = ", ";
503 this->writeExpression(*arg, kSequence_Precedence);
504 }
505 this->write(")");
506 }
Ethan Nicholas13863662019-07-29 13:05:15 -0400507 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample") {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400508 this->write(".%s");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400509 SkASSERT(c.fArguments.size() >= 1);
510 SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
John Stiles3dc0da62020-08-19 17:48:31 -0400511 String sampler = this->getSamplerHandle(c.fArguments[0]->as<VariableReference>().fVariable);
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400512 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
Greg Daniel369ee6b2019-12-02 15:30:02 -0500513 ").asString().c_str()");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400514 }
515}
516
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400517static const char* glsltype_string(const Context& context, const Type& type) {
518 if (type == *context.fFloat_Type) {
519 return "kFloat_GrSLType";
520 } else if (type == *context.fHalf_Type) {
521 return "kHalf_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400522 } else if (type == *context.fInt_Type) {
523 return "kInt_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400524 } else if (type == *context.fFloat2_Type) {
525 return "kFloat2_GrSLType";
526 } else if (type == *context.fHalf2_Type) {
527 return "kHalf2_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400528 } else if (type == *context.fInt2_Type) {
529 return "kInt2_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500530 } else if (type == *context.fFloat3_Type) {
531 return "kFloat3_GrSLType";
532 } else if (type == *context.fHalf3_Type) {
533 return "kHalf3_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400534 } else if (type == *context.fInt3_Type) {
535 return "kInt3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400536 } else if (type == *context.fFloat4_Type) {
537 return "kFloat4_GrSLType";
538 } else if (type == *context.fHalf4_Type) {
539 return "kHalf4_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400540 } else if (type == *context.fInt4_Type) {
541 return "kInt4_GrSLType";
Ethan Nicholas58430122020-04-14 09:54:02 -0400542 } else if (type == *context.fFloat2x2_Type) {
543 return "kFloat2x2_GrSLType";
544 } else if (type == *context.fHalf2x2_Type) {
545 return "kHalf2x2_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400546 } else if (type == *context.fFloat2x3_Type) {
547 return "kFloat2x3_GrSLType";
548 } else if (type == *context.fHalf2x3_Type) {
549 return "kHalf2x3_GrSLType";
550 } else if (type == *context.fFloat2x4_Type) {
551 return "kFloat2x4_GrSLType";
552 } else if (type == *context.fHalf2x4_Type) {
553 return "kHalf2x4_GrSLType";
554 } else if (type == *context.fFloat3x2_Type) {
555 return "kFloat3x2_GrSLType";
556 } else if (type == *context.fHalf3x2_Type) {
557 return "kHalf3x2_GrSLType";
Ethan Nicholas58430122020-04-14 09:54:02 -0400558 } else if (type == *context.fFloat3x3_Type) {
559 return "kFloat3x3_GrSLType";
560 } else if (type == *context.fHalf3x3_Type) {
561 return "kHalf3x3_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400562 } else if (type == *context.fFloat3x4_Type) {
563 return "kFloat3x4_GrSLType";
564 } else if (type == *context.fHalf3x4_Type) {
565 return "kHalf3x4_GrSLType";
566 } else if (type == *context.fFloat4x2_Type) {
567 return "kFloat4x2_GrSLType";
568 } else if (type == *context.fHalf4x2_Type) {
569 return "kHalf4x2_GrSLType";
570 } else if (type == *context.fFloat4x3_Type) {
571 return "kFloat4x3_GrSLType";
572 } else if (type == *context.fHalf4x3_Type) {
573 return "kHalf4x3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400574 } else if (type == *context.fFloat4x4_Type) {
575 return "kFloat4x4_GrSLType";
576 } else if (type == *context.fHalf4x4_Type) {
577 return "kHalf4x4_GrSLType";
578 } else if (type == *context.fVoid_Type) {
579 return "kVoid_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500580 } else if (type.kind() == Type::kEnum_Kind) {
581 return "int";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400582 }
583 SkASSERT(false);
584 return nullptr;
585}
586
Ethan Nicholas762466e2017-06-29 10:03:38 -0400587void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400588 const FunctionDeclaration& decl = f.fDeclaration;
Brian Osman08f986d2020-05-13 17:06:46 -0400589 if (decl.fBuiltin) {
590 return;
591 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400592 fFunctionHeader = "";
593 OutputStream* oldOut = fOut;
594 StringStream buffer;
595 fOut = &buffer;
596 if (decl.fName == "main") {
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400597 fInMain = true;
John Stiles3dc0da62020-08-19 17:48:31 -0400598 for (const auto& s : f.fBody->as<Block>().fStatements) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400599 this->writeStatement(*s);
600 this->writeLine();
601 }
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400602 fInMain = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400603
604 fOut = oldOut;
605 this->write(fFunctionHeader);
606 this->write(buffer.str());
607 } else {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400608 this->addExtraEmitCodeLine("SkString " + decl.fName + "_name;");
609 String args = "const GrShaderVar " + decl.fName + "_args[] = { ";
610 const char* separator = "";
611 for (const auto& param : decl.fParameters) {
612 args += String(separator) + "GrShaderVar(\"" + param->fName + "\", " +
613 glsltype_string(fContext, param->fType) + ")";
614 separator = ", ";
615 }
616 args += "};";
617 this->addExtraEmitCodeLine(args.c_str());
John Stiles3dc0da62020-08-19 17:48:31 -0400618 for (const auto& s : f.fBody->as<Block>().fStatements) {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400619 this->writeStatement(*s);
620 this->writeLine();
621 }
622
623 fOut = oldOut;
624 String emit = "fragBuilder->emitFunction(";
625 emit += glsltype_string(fContext, decl.fReturnType);
626 emit += ", \"" + decl.fName + "\"";
627 emit += ", " + to_string((int64_t) decl.fParameters.size());
628 emit += ", " + decl.fName + "_args";
John Stiles50819422020-06-18 13:00:38 -0400629 emit += ",\nR\"SkSL(" + buffer.str() + ")SkSL\"";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400630 emit += ", &" + decl.fName + "_name);";
631 this->addExtraEmitCodeLine(emit.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400632 }
633}
634
635void CPPCodeGenerator::writeSetting(const Setting& s) {
Brian Osmanf265afd2020-08-04 13:23:36 -0400636 this->write(s.fName.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400637}
638
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400639bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400640 const Section* s = fSectionAndParameterHelper.getSection(name);
641 if (s) {
642 this->writef("%s%s", prefix, s->fText.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400643 return true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400644 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400645 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400646}
647
648void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
649 if (p.fKind == ProgramElement::kSection_Kind) {
650 return;
651 }
652 if (p.fKind == ProgramElement::kVar_Kind) {
John Stiles3dc0da62020-08-19 17:48:31 -0400653 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400654 if (!decls.fVars.size()) {
655 return;
656 }
John Stiles3dc0da62020-08-19 17:48:31 -0400657 const Variable& var = *decls.fVars[0]->as<VarDeclaration>().fVar;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400658 if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
659 -1 != var.fModifiers.fLayout.fBuiltin) {
660 return;
661 }
662 }
663 INHERITED::writeProgramElement(p);
664}
665
666void CPPCodeGenerator::addUniform(const Variable& var) {
667 if (!needs_uniform_var(var)) {
668 return;
669 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400670 if (var.fModifiers.fLayout.fWhen.fLength) {
671 this->writef(" if (%s) {\n ", String(var.fModifiers.fLayout.fWhen).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400672 }
Ethan Nicholas95b24b92020-08-20 00:03:58 +0000673 const char* type = glsltype_string(fContext, var.fType);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700674 String name(var.fName);
Ethan Nicholas95b24b92020-08-20 00:03:58 +0000675 this->writef(" %sVar = args.fUniformHandler->addUniform(&_outer, kFragment_GrShaderFlag,"
676 " %s, \"%s\");\n", HCodeGenerator::FieldName(name.c_str()).c_str(), type,
677 name.c_str());
Ethan Nicholasfc994162019-06-06 10:04:27 -0400678 if (var.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400679 this->write(" }\n");
680 }
681}
682
Ethan Nicholascd700e92018-08-24 16:43:57 -0400683void CPPCodeGenerator::writeInputVars() {
684}
685
Ethan Nicholas762466e2017-06-29 10:03:38 -0400686void CPPCodeGenerator::writePrivateVars() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400687 for (const auto& p : fProgram) {
688 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -0400689 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400690 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -0400691 VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000692 if (is_private(*decl.fVar)) {
693 if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
694 fErrors.error(decl.fOffset,
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400695 "fragmentProcessor variables must be declared 'in'");
696 return;
697 }
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500698 this->writef("%s %s = %s;\n",
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000699 HCodeGenerator::FieldType(fContext, decl.fVar->fType,
700 decl.fVar->fModifiers.fLayout).c_str(),
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500701 String(decl.fVar->fName).c_str(),
702 default_value(*decl.fVar).c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400703 } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
704 // An auto-tracked uniform in variable, so add a field to hold onto the prior
705 // state. Note that tracked variables must be uniform in's and that is validated
706 // before writePrivateVars() is called.
707 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
708 SkASSERT(mapper && mapper->supportsTracking());
709
710 String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
711 // The member statement is different if the mapper reports a default value
712 if (mapper->defaultValue().size() > 0) {
713 this->writef("%s %sPrev = %s;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400714 Layout::CTypeToStr(mapper->ctype()), name.c_str(),
Michael Ludwiga4275592018-08-31 10:52:47 -0400715 mapper->defaultValue().c_str());
716 } else {
717 this->writef("%s %sPrev;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400718 Layout::CTypeToStr(mapper->ctype()), name.c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400719 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400720 }
721 }
722 }
723 }
724}
725
726void CPPCodeGenerator::writePrivateVarValues() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400727 for (const auto& p : fProgram) {
728 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -0400729 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400730 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -0400731 VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000732 if (is_private(*decl.fVar) && decl.fValue) {
733 this->writef("%s = ", String(decl.fVar->fName).c_str());
Ethan Nicholas82399462017-10-16 12:35:44 -0400734 fCPPMode = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000735 this->writeExpression(*decl.fValue, kAssignment_Precedence);
Ethan Nicholas82399462017-10-16 12:35:44 -0400736 fCPPMode = false;
737 this->write(";\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400738 }
739 }
740 }
741 }
742}
743
Ethan Nicholas82399462017-10-16 12:35:44 -0400744static bool is_accessible(const Variable& var) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500745 const Type& type = var.fType.nonnullable();
746 return Type::kSampler_Kind != type.kind() &&
747 Type::kOther_Kind != type.kind();
Ethan Nicholas82399462017-10-16 12:35:44 -0400748}
749
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400750void CPPCodeGenerator::newExtraEmitCodeBlock() {
751 // This should only be called when emitting SKSL for emitCode(), which can be detected if the
752 // cpp buffer is not null, and the cpp buffer is not the current output.
753 SkASSERT(fCPPBuffer && fCPPBuffer != fOut);
754
755 // Start a new block as an empty string
756 fExtraEmitCodeBlocks.push_back("");
757 // Mark its location in the output buffer, uses ${\d} for the token since ${} will not occur in
758 // valid sksl and makes detection trivial.
759 this->writef("${%zu}", fExtraEmitCodeBlocks.size() - 1);
760}
761
762void CPPCodeGenerator::addExtraEmitCodeLine(const String& toAppend) {
763 SkASSERT(fExtraEmitCodeBlocks.size() > 0);
764 String& currentBlock = fExtraEmitCodeBlocks[fExtraEmitCodeBlocks.size() - 1];
765 // Automatically add indentation and newline
766 currentBlock += " " + toAppend + "\n";
767}
768
769void CPPCodeGenerator::flushEmittedCode() {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400770 if (fCPPBuffer == nullptr) {
771 // Not actually within writeEmitCode() so nothing to flush
772 return;
773 }
774
775 StringStream* skslBuffer = static_cast<StringStream*>(fOut);
776
777 String sksl = skslBuffer->str();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400778 // Empty the accumulation buffer since its current contents are consumed.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400779 skslBuffer->reset();
780
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400781 // Switch to the cpp buffer
Michael Ludwigd0440192018-09-07 14:24:52 +0000782 fOut = fCPPBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400783
784 // Iterate through the sksl, keeping track of where the last statement ended (e.g. the latest
785 // encountered ';', '{', or '}'). If an extra emit code block token is encountered then the
786 // code from 0 to last statement end is sent to writeCodeAppend, the extra code block is
787 // appended to the cpp buffer, and then the sksl string is trimmed to start where the last
788 // statement left off (minus the encountered token).
789 size_t i = 0;
790 int flushPoint = -1;
791 int tokenStart = -1;
792 while (i < sksl.size()) {
793 if (tokenStart >= 0) {
794 // Looking for the end of the token
795 if (sksl[i] == '}') {
796 // Must append the sksl from 0 to flushPoint (inclusive) then the extra code
797 // accumulated in the block with index parsed from chars [tokenStart+2, i-1]
798 String toFlush = String(sksl.c_str(), flushPoint + 1);
799 // writeCodeAppend automatically removes the format args that it consumed, so
800 // fFormatArgs will be in a valid state for any future sksl
801 this->writeCodeAppend(toFlush);
802
803 int codeBlock = stoi(String(sksl.c_str() + tokenStart + 2, i - tokenStart - 2));
804 SkASSERT(codeBlock < (int) fExtraEmitCodeBlocks.size());
805 if (fExtraEmitCodeBlocks[codeBlock].size() > 0) {
806 this->write(fExtraEmitCodeBlocks[codeBlock].c_str());
807 }
808
809 // Now reset the sksl buffer to start after the flush point, but remove the token.
810 String compacted = String(sksl.c_str() + flushPoint + 1,
811 tokenStart - flushPoint - 1);
812 if (i < sksl.size() - 1) {
813 compacted += String(sksl.c_str() + i + 1, sksl.size() - i - 1);
814 }
815 sksl = compacted;
816
817 // And reset iteration
818 i = -1;
819 flushPoint = -1;
820 tokenStart = -1;
821 }
822 } else {
823 // Looking for the start of extra emit block tokens, and tracking when statements end
824 if (sksl[i] == ';' || sksl[i] == '{' || sksl[i] == '}') {
825 flushPoint = i;
826 } else if (i < sksl.size() - 1 && sksl[i] == '$' && sksl[i + 1] == '{') {
827 // found an extra emit code block token
828 tokenStart = i++;
829 }
830 }
831 i++;
Michael Ludwigd0440192018-09-07 14:24:52 +0000832 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400833
834 // Once we've gone through the sksl string to this point, there are no remaining extra emit
835 // code blocks to interleave, so append the remainder as usual.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400836 this->writeCodeAppend(sksl);
837
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400838 // After appending, switch back to the emptied sksl buffer and reset the extra code blocks
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400839 fOut = skslBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400840 fExtraEmitCodeBlocks.clear();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400841}
842
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400843void CPPCodeGenerator::writeCodeAppend(const String& code) {
John Stiles50819422020-06-18 13:00:38 -0400844 if (!code.empty()) {
845 // Count % format specifiers.
846 size_t argCount = 0;
847 for (size_t index = 0; index < code.size(); ++index) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400848 if ('%' == code[index]) {
John Stiles50819422020-06-18 13:00:38 -0400849 if (index == code.size() - 1) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400850 break;
851 }
852 if (code[index + 1] != '%') {
853 ++argCount;
854 }
855 }
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400856 }
John Stiles50819422020-06-18 13:00:38 -0400857
858 // Emit the code string.
859 this->writef(" fragBuilder->codeAppendf(\n"
860 "R\"SkSL(%s)SkSL\"\n", code.c_str());
861 for (size_t i = 0; i < argCount; ++i) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400862 this->writef(", %s", fFormatArgs[i].c_str());
863 }
864 this->write(");\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400865
John Stiles50819422020-06-18 13:00:38 -0400866 // argCount is equal to the number of fFormatArgs that were consumed, so they should be
867 // removed from the list.
868 if (argCount > 0) {
869 fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argCount);
870 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400871 }
872}
873
874String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
875 const String& cppVar) {
876 // To do this conversion, we temporarily switch the sksl output stream
877 // to an empty stringstream and reset the format args to empty.
878 OutputStream* oldSKSL = fOut;
879 StringStream exprBuffer;
880 fOut = &exprBuffer;
881
882 std::vector<String> oldArgs(fFormatArgs);
883 fFormatArgs.clear();
884
885 // Convert the argument expression into a format string and args
886 this->writeExpression(e, Precedence::kTopLevel_Precedence);
887 std::vector<String> newArgs(fFormatArgs);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400888 String expr = exprBuffer.str();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400889
890 // After generating, restore the original output stream and format args
891 fFormatArgs = oldArgs;
892 fOut = oldSKSL;
893
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400894 // The sksl written to exprBuffer is not processed by flushEmittedCode(), so any extra emit code
895 // block tokens won't get handled. So we need to strip them from the expression and stick them
896 // to the end of the original sksl stream.
897 String exprFormat = "";
898 int tokenStart = -1;
899 for (size_t i = 0; i < expr.size(); i++) {
900 if (tokenStart >= 0) {
901 if (expr[i] == '}') {
902 // End of the token, so append the token to fOut
903 fOut->write(expr.c_str() + tokenStart, i - tokenStart + 1);
904 tokenStart = -1;
905 }
906 } else {
907 if (i < expr.size() - 1 && expr[i] == '$' && expr[i + 1] == '{') {
908 tokenStart = i++;
909 } else {
910 exprFormat += expr[i];
911 }
912 }
913 }
914
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400915 // Now build the final C++ code snippet from the format string and args
916 String cppExpr;
John Stiles50819422020-06-18 13:00:38 -0400917 if (newArgs.empty()) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400918 // This was a static expression, so we can simplify the input
919 // color declaration in the emitted code to just a static string
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400920 cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");";
John Stiles50819422020-06-18 13:00:38 -0400921 } else if (newArgs.size() == 1 && exprFormat == "%s") {
922 // If the format expression is simply "%s", we can avoid an expensive call to printf.
923 // This happens fairly often in codegen so it is worth simplifying.
924 cppExpr = "SkString " + cppVar + "(" + newArgs[0] + ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400925 } else {
926 // String formatting must occur dynamically, so have the C++ declaration
927 // use SkStringPrintf with the format args that were accumulated
928 // when the expression was written.
929 cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
930 for (size_t i = 0; i < newArgs.size(); i++) {
931 cppExpr += ", " + newArgs[i];
932 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400933 cppExpr += ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400934 }
935 return cppExpr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400936}
937
Ethan Nicholas762466e2017-06-29 10:03:38 -0400938bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
939 this->write(" void emitCode(EmitArgs& args) override {\n"
940 " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
941 this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
942 " (void) _outer;\n",
943 fFullName.c_str(), fFullName.c_str());
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400944 for (const auto& p : fProgram) {
945 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -0400946 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400947 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -0400948 VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000949 String nameString(decl.fVar->fName);
Ethan Nicholas82399462017-10-16 12:35:44 -0400950 const char* name = nameString.c_str();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000951 if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
952 is_accessible(*decl.fVar)) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400953 this->writef(" auto %s = _outer.%s;\n"
Ethan Nicholas82399462017-10-16 12:35:44 -0400954 " (void) %s;\n",
955 name, name, name);
956 }
957 }
958 }
959 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400960 this->writePrivateVarValues();
961 for (const auto u : uniforms) {
962 this->addUniform(*u);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400963 }
John Stiles02b11282020-08-10 15:25:24 -0400964 this->writeSection(kEmitCodeSection);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400965
966 // Save original buffer as the CPP buffer for flushEmittedCode()
967 fCPPBuffer = fOut;
968 StringStream skslBuffer;
969 fOut = &skslBuffer;
970
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400971 this->newExtraEmitCodeBlock();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400972 bool result = INHERITED::generateCode();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400973 this->flushEmittedCode();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400974
975 // Then restore the original CPP buffer and close the function
976 fOut = fCPPBuffer;
977 fCPPBuffer = nullptr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400978 this->write(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400979 return result;
980}
981
982void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
983 const char* fullName = fFullName.c_str();
John Stiles02b11282020-08-10 15:25:24 -0400984 const Section* section = fSectionAndParameterHelper.getSection(kSetDataSection);
Ethan Nicholas68990be2017-07-13 09:36:52 -0400985 const char* pdman = section ? section->fArgument.c_str() : "pdman";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400986 this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
987 "const GrFragmentProcessor& _proc) override {\n",
988 pdman);
989 bool wroteProcessor = false;
John Stiles06f3d082020-06-04 11:07:21 -0400990 for (const Variable* u : uniforms) {
Michael Ludwiga4275592018-08-31 10:52:47 -0400991 if (is_uniform_in(*u)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400992 if (!wroteProcessor) {
993 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
994 wroteProcessor = true;
995 this->writef(" {\n");
996 }
Michael Ludwiga4275592018-08-31 10:52:47 -0400997
998 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
999 SkASSERT(mapper);
1000
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001001 String nameString(u->fName);
1002 const char* name = nameString.c_str();
Michael Ludwiga4275592018-08-31 10:52:47 -04001003
1004 // Switches for setData behavior in the generated code
1005 bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
1006 bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
1007 bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
1008
1009 String uniformName = HCodeGenerator::FieldName(name) + "Var";
1010
1011 String indent = " "; // 8 by default, 12 when nested for conditional uniforms
1012 if (conditionalUniform) {
1013 // Add a pre-check to make sure the uniform was emitted
1014 // before trying to send any data to the GPU
1015 this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
1016 indent += " ";
1017 }
1018
1019 String valueVar = "";
1020 if (needsValueDeclaration) {
1021 valueVar.appendf("%sValue", name);
1022 // Use AccessType since that will match the return type of _outer's public API.
1023 String valueType = HCodeGenerator::AccessType(fContext, u->fType,
1024 u->fModifiers.fLayout);
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001025 this->writef("%s%s %s = _outer.%s;\n",
Michael Ludwiga4275592018-08-31 10:52:47 -04001026 indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001027 } else {
Michael Ludwiga4275592018-08-31 10:52:47 -04001028 // Not tracked and the mapper only needs to use the value once
1029 // so send it a safe expression instead of the variable name
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001030 valueVar.appendf("(_outer.%s)", name);
Michael Ludwiga4275592018-08-31 10:52:47 -04001031 }
1032
1033 if (isTracked) {
1034 SkASSERT(mapper->supportsTracking());
1035
1036 String prevVar = HCodeGenerator::FieldName(name) + "Prev";
1037 this->writef("%sif (%s) {\n"
1038 "%s %s;\n"
1039 "%s %s;\n"
1040 "%s}\n", indent.c_str(),
1041 mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
1042 mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
1043 mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
1044 } else {
1045 this->writef("%s%s;\n", indent.c_str(),
1046 mapper->setUniform(pdman, uniformName, valueVar).c_str());
1047 }
1048
1049 if (conditionalUniform) {
1050 // Close the earlier precheck block
1051 this->writef(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001052 }
1053 }
1054 }
1055 if (wroteProcessor) {
1056 this->writef(" }\n");
1057 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001058 if (section) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001059 int samplerIndex = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001060 for (const auto& p : fProgram) {
1061 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001062 const VarDeclarations& decls = p.as<VarDeclarations>();
John Stiles06f3d082020-06-04 11:07:21 -04001063 for (const std::unique_ptr<Statement>& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001064 const VarDeclaration& decl = raw->as<VarDeclaration>();
John Stiles06f3d082020-06-04 11:07:21 -04001065 const Variable& variable = *decl.fVar;
1066 String nameString(variable.fName);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001067 const char* name = nameString.c_str();
John Stiles06f3d082020-06-04 11:07:21 -04001068 if (variable.fType.kind() == Type::kSampler_Kind) {
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001069 this->writef(" const GrSurfaceProxyView& %sView = "
1070 "_outer.textureSampler(%d).view();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001071 name, samplerIndex);
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001072 this->writef(" GrTexture& %s = *%sView.proxy()->peekTexture();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001073 name, name);
1074 this->writef(" (void) %s;\n", name);
1075 ++samplerIndex;
John Stiles06f3d082020-06-04 11:07:21 -04001076 } else if (needs_uniform_var(variable)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001077 this->writef(" UniformHandle& %s = %sVar;\n"
1078 " (void) %s;\n",
1079 name, HCodeGenerator::FieldName(name).c_str(), name);
John Stiles06f3d082020-06-04 11:07:21 -04001080 } else if (SectionAndParameterHelper::IsParameter(variable) &&
1081 variable.fType != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001082 if (!wroteProcessor) {
1083 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
1084 fullName);
1085 wroteProcessor = true;
1086 }
John Stiles06f3d082020-06-04 11:07:21 -04001087
1088 if (variable.fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
1089 this->writef(" auto %s = _outer.%s;\n"
1090 " (void) %s;\n",
1091 name, name, name);
1092 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001093 }
1094 }
1095 }
1096 }
John Stiles02b11282020-08-10 15:25:24 -04001097 this->writeSection(kSetDataSection);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001098 }
1099 this->write(" }\n");
1100}
1101
Brian Salomonf7dcd762018-07-30 14:48:15 -04001102void CPPCodeGenerator::writeOnTextureSampler() {
1103 bool foundSampler = false;
1104 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1105 if (param->fType.kind() == Type::kSampler_Kind) {
1106 if (!foundSampler) {
1107 this->writef(
1108 "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
1109 "index) const {\n",
1110 fFullName.c_str());
1111 this->writef(" return IthTextureSampler(index, %s",
1112 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1113 foundSampler = true;
1114 } else {
1115 this->writef(", %s",
1116 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1117 }
1118 }
1119 }
1120 if (foundSampler) {
1121 this->write(");\n}\n");
1122 }
1123}
1124
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001125void CPPCodeGenerator::writeClone() {
John Stiles02b11282020-08-10 15:25:24 -04001126 if (!this->writeSection(kCloneSection)) {
1127 if (fSectionAndParameterHelper.getSection(kFieldsSection)) {
John Stiles47b4e222020-08-12 09:56:50 -04001128 fErrors.error(/*offset=*/0, "fragment processors with custom @fields must also have a "
1129 "custom @clone");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001130 }
1131 this->writef("%s::%s(const %s& src)\n"
Ethan Nicholasabff9562017-10-09 10:54:08 -04001132 ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
1133 fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
John Stiles06f3d082020-06-04 11:07:21 -04001134 for (const Variable* param : fSectionAndParameterHelper.getParameters()) {
Robert Phillipsbce7d862019-02-21 22:53:57 +00001135 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
John Stiles88183902020-06-10 16:40:38 -04001136 if (param->fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001137 this->writef("\n, %s(src.%s)",
1138 fieldName.c_str(),
1139 fieldName.c_str());
1140 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001141 }
Ethan Nicholasabff9562017-10-09 10:54:08 -04001142 this->writef(" {\n");
Brian Osman12c5d292020-07-13 16:11:35 -04001143 this->writef(" this->cloneAndRegisterAllChildProcessors(src);\n");
Brian Salomonf7dcd762018-07-30 14:48:15 -04001144 int samplerCount = 0;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001145 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1146 if (param->fType.kind() == Type::kSampler_Kind) {
Brian Salomonf7dcd762018-07-30 14:48:15 -04001147 ++samplerCount;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001148 }
1149 }
Brian Salomonf7dcd762018-07-30 14:48:15 -04001150 if (samplerCount) {
1151 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
1152 }
Michael Ludwige88320b2020-06-24 09:04:56 -04001153 if (fAccessSampleCoordsDirectly) {
1154 this->writef(" this->setUsesSampleCoordsDirectly();\n");
1155 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001156 this->write("}\n");
Brian Salomonaff329b2017-08-11 09:40:37 -04001157 this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
1158 fFullName.c_str());
John Stilesfbd050b2020-08-03 13:21:46 -04001159 this->writef(" return std::make_unique<%s>(*this);\n",
Brian Salomonaff329b2017-08-11 09:40:37 -04001160 fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001161 this->write("}\n");
1162 }
1163}
1164
John Stiles47b4e222020-08-12 09:56:50 -04001165void CPPCodeGenerator::writeDumpInfo() {
John Stiles8d9bf642020-08-12 15:07:45 -04001166 this->writef("#if GR_TEST_UTILS\n"
John Stilescab58862020-08-12 15:47:06 -04001167 "SkString %s::onDumpInfo() const {\n", fFullName.c_str());
John Stiles47b4e222020-08-12 09:56:50 -04001168
1169 if (!this->writeSection(kDumpInfoSection)) {
1170 if (fSectionAndParameterHelper.getSection(kFieldsSection)) {
1171 fErrors.error(/*offset=*/0, "fragment processors with custom @fields must also have a "
1172 "custom @dumpInfo");
1173 }
1174
John Stiles47b4e222020-08-12 09:56:50 -04001175 String formatString;
1176 std::vector<String> argumentList;
1177
1178 for (const Variable* param : fSectionAndParameterHelper.getParameters()) {
1179 // dumpInfo() doesn't need to log child FPs.
1180 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
1181 continue;
1182 }
1183
1184 // Add this field onto the format string and argument list.
1185 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
1186 String runtimeValue = this->formatRuntimeValue(param->fType, param->fModifiers.fLayout,
1187 param->fName, &argumentList);
1188 formatString.appendf("%s%s=%s",
1189 formatString.empty() ? "" : ", ",
1190 fieldName.c_str(),
1191 runtimeValue.c_str());
1192 }
1193
John Stiles47b4e222020-08-12 09:56:50 -04001194 if (!formatString.empty()) {
John Stilescab58862020-08-12 15:47:06 -04001195 // Emit the finished format string and associated arguments.
1196 this->writef(" return SkStringPrintf(\"(%s)\"", formatString.c_str());
John Stiles47b4e222020-08-12 09:56:50 -04001197
John Stilescab58862020-08-12 15:47:06 -04001198 for (const String& argument : argumentList) {
1199 this->writef(", %s", argument.c_str());
1200 }
John Stiles47b4e222020-08-12 09:56:50 -04001201
John Stilescab58862020-08-12 15:47:06 -04001202 this->write(");");
1203 } else {
1204 // No fields to dump at all; just return an empty string.
1205 this->write(" return SkString();");
1206 }
John Stiles47b4e222020-08-12 09:56:50 -04001207 }
1208
John Stilescab58862020-08-12 15:47:06 -04001209 this->write("\n"
1210 "}\n"
John Stiles47b4e222020-08-12 09:56:50 -04001211 "#endif\n");
1212}
1213
Ethan Nicholas762466e2017-06-29 10:03:38 -04001214void CPPCodeGenerator::writeTest() {
John Stiles02b11282020-08-10 15:25:24 -04001215 const Section* test = fSectionAndParameterHelper.getSection(kTestCodeSection);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001216 if (test) {
Brian Salomonaff329b2017-08-11 09:40:37 -04001217 this->writef(
1218 "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
1219 "#if GR_TEST_UTILS\n"
1220 "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
1221 fFullName.c_str(),
1222 fFullName.c_str(),
1223 test->fArgument.c_str());
John Stiles02b11282020-08-10 15:25:24 -04001224 this->writeSection(kTestCodeSection);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001225 this->write("}\n"
1226 "#endif\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001227 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001228}
1229
1230void CPPCodeGenerator::writeGetKey() {
1231 this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
1232 "GrProcessorKeyBuilder* b) const {\n",
1233 fFullName.c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001234 for (const auto& p : fProgram) {
1235 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001236 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholascab767f2019-07-01 13:32:07 -04001237 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001238 const VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholascab767f2019-07-01 13:32:07 -04001239 const Variable& var = *decl.fVar;
1240 String nameString(var.fName);
1241 const char* name = nameString.c_str();
1242 if (var.fModifiers.fLayout.fKey != Layout::kNo_Key &&
1243 (var.fModifiers.fFlags & Modifiers::kUniform_Flag)) {
1244 fErrors.error(var.fOffset,
1245 "layout(key) may not be specified on uniforms");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001246 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001247 switch (var.fModifiers.fLayout.fKey) {
1248 case Layout::kKey_Key:
1249 if (is_private(var)) {
1250 this->writef("%s %s =",
1251 HCodeGenerator::FieldType(fContext, var.fType,
1252 var.fModifiers.fLayout).c_str(),
1253 String(var.fName).c_str());
1254 if (decl.fValue) {
1255 fCPPMode = true;
1256 this->writeExpression(*decl.fValue, kAssignment_Precedence);
1257 fCPPMode = false;
1258 } else {
1259 this->writef("%s", default_value(var).c_str());
1260 }
1261 this->write(";\n");
1262 }
1263 if (var.fModifiers.fLayout.fWhen.fLength) {
1264 this->writef("if (%s) {", String(var.fModifiers.fLayout.fWhen).c_str());
1265 }
John Stilesb3038f82020-07-27 17:33:25 -04001266 if (var.fType == *fContext.fHalf4_Type) {
Ethan Nicholascab767f2019-07-01 13:32:07 -04001267 this->writef(" uint16_t red = SkFloatToHalf(%s.fR);\n",
1268 HCodeGenerator::FieldName(name).c_str());
1269 this->writef(" uint16_t green = SkFloatToHalf(%s.fG);\n",
1270 HCodeGenerator::FieldName(name).c_str());
1271 this->writef(" uint16_t blue = SkFloatToHalf(%s.fB);\n",
1272 HCodeGenerator::FieldName(name).c_str());
1273 this->writef(" uint16_t alpha = SkFloatToHalf(%s.fA);\n",
1274 HCodeGenerator::FieldName(name).c_str());
1275 this->write(" b->add32(((uint32_t)red << 16) | green);\n");
1276 this->write(" b->add32(((uint32_t)blue << 16) | alpha);\n");
John Stiles45f5b032020-07-27 17:31:29 -04001277 } else if (var.fType == *fContext.fHalf_Type ||
1278 var.fType == *fContext.fFloat_Type) {
1279 this->writef(" b->add32(sk_bit_cast<uint32_t>(%s));\n",
Ethan Nicholascab767f2019-07-01 13:32:07 -04001280 HCodeGenerator::FieldName(name).c_str());
John Stiles45f5b032020-07-27 17:31:29 -04001281 } else if (var.fType.isInteger() || var.fType == *fContext.fBool_Type ||
1282 var.fType.kind() == Type::kEnum_Kind) {
1283 this->writef(" b->add32((uint32_t) %s);\n",
1284 HCodeGenerator::FieldName(name).c_str());
1285 } else {
1286 ABORT("NOT YET IMPLEMENTED: automatic key handling for %s\n",
1287 var.fType.displayName().c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001288 }
1289 if (var.fModifiers.fLayout.fWhen.fLength) {
1290 this->write("}");
1291 }
1292 break;
1293 case Layout::kIdentity_Key:
1294 if (var.fType.kind() != Type::kMatrix_Kind) {
1295 fErrors.error(var.fOffset,
1296 "layout(key=identity) requires matrix type");
1297 }
1298 this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
1299 HCodeGenerator::FieldName(name).c_str());
1300 break;
1301 case Layout::kNo_Key:
1302 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001303 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001304 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001305 }
1306 }
1307 this->write("}\n");
1308}
1309
1310bool CPPCodeGenerator::generateCode() {
1311 std::vector<const Variable*> uniforms;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001312 for (const auto& p : fProgram) {
1313 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001314 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001315 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001316 VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001317 if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1318 decl.fVar->fType.kind() != Type::kSampler_Kind) {
1319 uniforms.push_back(decl.fVar);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001320 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001321
1322 if (is_uniform_in(*decl.fVar)) {
1323 // Validate the "uniform in" declarations to make sure they are fully supported,
1324 // instead of generating surprising C++
1325 const UniformCTypeMapper* mapper =
1326 UniformCTypeMapper::Get(fContext, *decl.fVar);
1327 if (mapper == nullptr) {
1328 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1329 + "'s type is not supported for use as a 'uniform in'");
1330 return false;
1331 }
1332 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1333 if (!mapper->supportsTracking()) {
1334 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1335 + "'s type does not support state tracking");
1336 return false;
1337 }
1338 }
1339
1340 } else {
1341 // If it's not a uniform_in, it's an error to be tracked
1342 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1343 fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
1344 return false;
1345 }
1346 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001347 }
1348 }
1349 }
1350 const char* baseName = fName.c_str();
1351 const char* fullName = fFullName.c_str();
Ethan Nicholas130fb3f2018-02-01 12:14:34 -05001352 this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001353 this->writef(kFragmentProcessorHeader, fullName);
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001354 this->writef("#include \"%s.h\"\n\n", fullName);
John Stiles02b11282020-08-10 15:25:24 -04001355 this->writeSection(kCppSection);
John Stiles45f5b032020-07-27 17:31:29 -04001356 this->writef("#include \"src/core/SkUtils.h\"\n"
1357 "#include \"src/gpu/GrTexture.h\"\n"
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001358 "#include \"src/gpu/glsl/GrGLSLFragmentProcessor.h\"\n"
1359 "#include \"src/gpu/glsl/GrGLSLFragmentShaderBuilder.h\"\n"
1360 "#include \"src/gpu/glsl/GrGLSLProgramBuilder.h\"\n"
1361 "#include \"src/sksl/SkSLCPP.h\"\n"
1362 "#include \"src/sksl/SkSLUtil.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001363 "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
1364 "public:\n"
1365 " GrGLSL%s() {}\n",
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001366 baseName, baseName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001367 bool result = this->writeEmitCode(uniforms);
1368 this->write("private:\n");
1369 this->writeSetData(uniforms);
1370 this->writePrivateVars();
1371 for (const auto& u : uniforms) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001372 if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001373 this->writef(" UniformHandle %sVar;\n",
1374 HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001375 }
1376 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001377 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001378 if (needs_uniform_var(*param)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001379 this->writef(" UniformHandle %sVar;\n",
1380 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001381 }
1382 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001383 this->writef("};\n"
1384 "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
1385 " return new GrGLSL%s();\n"
1386 "}\n",
1387 fullName, baseName);
1388 this->writeGetKey();
1389 this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
1390 " const %s& that = other.cast<%s>();\n"
1391 " (void) that;\n",
1392 fullName, fullName, fullName);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001393 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001394 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001395 continue;
1396 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001397 String nameString(param->fName);
1398 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001399 this->writef(" if (%s != that.%s) return false;\n",
1400 HCodeGenerator::FieldName(name).c_str(),
1401 HCodeGenerator::FieldName(name).c_str());
1402 }
1403 this->write(" return true;\n"
1404 "}\n");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001405 this->writeClone();
John Stiles47b4e222020-08-12 09:56:50 -04001406 this->writeDumpInfo();
Brian Salomonf7dcd762018-07-30 14:48:15 -04001407 this->writeOnTextureSampler();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001408 this->writeTest();
John Stiles02b11282020-08-10 15:25:24 -04001409 this->writeSection(kCppEndSection);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001410
Ethan Nicholas762466e2017-06-29 10:03:38 -04001411 result &= 0 == fErrors.errorCount();
1412 return result;
1413}
1414
John Stilesa6841be2020-08-06 14:11:56 -04001415} // namespace SkSL