blob: da8e3eb06741a29931e655b4ea1b638158424dbd [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 Nicholas2a479a52020-08-18 16:29:45 -040018#if defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
19
Ethan Nicholas762466e2017-06-29 10:03:38 -040020namespace SkSL {
21
22static bool needs_uniform_var(const Variable& var) {
Ethan Nicholas5f9836e2017-12-20 15:16:33 -050023 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
24 var.fType.kind() != Type::kSampler_Kind;
Ethan Nicholas762466e2017-06-29 10:03:38 -040025}
26
27CPPCodeGenerator::CPPCodeGenerator(const Context* context, const Program* program,
28 ErrorReporter* errors, String name, OutputStream* out)
John Stiles50819422020-06-18 13:00:38 -040029 : INHERITED(context, program, errors, out)
30 , fName(std::move(name))
31 , fFullName(String::printf("Gr%s", fName.c_str()))
32 , fSectionAndParameterHelper(program, *errors) {
33 fLineEnding = "\n";
Ethan Nicholas13863662019-07-29 13:05:15 -040034 fTextureFunctionOverride = "sample";
Ethan Nicholas762466e2017-06-29 10:03:38 -040035}
36
37void CPPCodeGenerator::writef(const char* s, va_list va) {
38 static constexpr int BUFFER_SIZE = 1024;
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040039 va_list copy;
40 va_copy(copy, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040041 char buffer[BUFFER_SIZE];
John Stiles50819422020-06-18 13:00:38 -040042 int length = std::vsnprintf(buffer, BUFFER_SIZE, s, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040043 if (length < BUFFER_SIZE) {
44 fOut->write(buffer, length);
45 } else {
46 std::unique_ptr<char[]> heap(new char[length + 1]);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040047 vsprintf(heap.get(), s, copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040048 fOut->write(heap.get(), length);
49 }
z102.zhangd74f2c82018-08-10 09:08:47 +080050 va_end(copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040051}
52
53void CPPCodeGenerator::writef(const char* s, ...) {
54 va_list va;
55 va_start(va, s);
56 this->writef(s, va);
57 va_end(va);
58}
59
60void CPPCodeGenerator::writeHeader() {
61}
62
Ethan Nicholasf7b88202017-09-18 14:10:39 -040063bool CPPCodeGenerator::usesPrecisionModifiers() const {
64 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -040065}
66
Ethan Nicholasf7b88202017-09-18 14:10:39 -040067String CPPCodeGenerator::getTypeName(const Type& type) {
68 return type.name();
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040069}
Ethan Nicholasf7b88202017-09-18 14:10:39 -040070
Ethan Nicholas762466e2017-06-29 10:03:38 -040071void CPPCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
72 Precedence parentPrecedence) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040073 if (b.fOperator == Token::Kind::TK_PERCENT) {
Ethan Nicholas762466e2017-06-29 10:03:38 -040074 // need to use "%%" instead of "%" b/c the code will be inside of a printf
75 Precedence precedence = GetBinaryPrecedence(b.fOperator);
76 if (precedence >= parentPrecedence) {
77 this->write("(");
78 }
79 this->writeExpression(*b.fLeft, precedence);
80 this->write(" %% ");
81 this->writeExpression(*b.fRight, precedence);
82 if (precedence >= parentPrecedence) {
83 this->write(")");
84 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050085 } else if (b.fLeft->fKind == Expression::kNullLiteral_Kind ||
86 b.fRight->fKind == Expression::kNullLiteral_Kind) {
87 const Variable* var;
88 if (b.fLeft->fKind != Expression::kNullLiteral_Kind) {
John Stiles17c5b702020-08-18 10:40:03 -040089 var = &b.fLeft->as<VariableReference>().fVariable;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050090 } else {
John Stiles17c5b702020-08-18 10:40:03 -040091 var = &b.fRight->as<VariableReference>().fVariable;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050092 }
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
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400115static String default_value(const Type& type) {
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500116 if (type.fName == "bool") {
117 return "false";
118 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400119 switch (type.kind()) {
120 case Type::kScalar_Kind: return "0";
121 case Type::kVector_Kind: return type.name() + "(0)";
122 case Type::kMatrix_Kind: return type.name() + "(1)";
123 default: ABORT("unsupported default_value type\n");
124 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400125}
126
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500127static String default_value(const Variable& var) {
Brian Osman495993a2018-10-16 15:45:55 -0400128 if (var.fModifiers.fLayout.fCType == SkSL::Layout::CType::kSkPMColor4f) {
Brian Osmanf28e55d2018-10-03 16:35:54 -0400129 return "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}";
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500130 }
131 return default_value(var.fType);
132}
133
Ethan Nicholas762466e2017-06-29 10:03:38 -0400134static bool is_private(const Variable& var) {
135 return !(var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
136 !(var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
137 var.fStorage == Variable::kGlobal_Storage &&
138 var.fModifiers.fLayout.fBuiltin == -1;
139}
140
Michael Ludwiga4275592018-08-31 10:52:47 -0400141static bool is_uniform_in(const Variable& var) {
142 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
143 (var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
144 var.fType.kind() != Type::kSampler_Kind;
145}
146
John Stiles47b4e222020-08-12 09:56:50 -0400147String CPPCodeGenerator::formatRuntimeValue(const Type& type,
148 const Layout& layout,
149 const String& cppCode,
150 std::vector<String>* formatArgs) {
Ethan Nicholas7018bcf2020-08-20 15:57:22 -0400151 if (type.kind() == Type::kArray_Kind) {
152 String result("[");
153 const char* separator = "";
154 for (int i = 0; i < type.columns(); i++) {
155 result += separator + this->formatRuntimeValue(type.componentType(), layout,
156 "(" + cppCode + ")[" + to_string(i) +
157 "]", formatArgs);
158 separator = ",";
159 }
160 result += "]";
161 return result;
162 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400163 if (type.isFloat()) {
John Stiles47b4e222020-08-12 09:56:50 -0400164 formatArgs->push_back(cppCode);
165 return "%f";
166 }
167 if (type == *fContext.fInt_Type) {
168 formatArgs->push_back(cppCode);
169 return "%d";
170 }
171 if (type == *fContext.fBool_Type) {
172 formatArgs->push_back("(" + cppCode + " ? \"true\" : \"false\")");
173 return "%s";
174 }
175 if (type == *fContext.fFloat2_Type || type == *fContext.fHalf2_Type) {
176 formatArgs->push_back(cppCode + ".fX");
177 formatArgs->push_back(cppCode + ".fY");
178 return type.name() + "(%f, %f)";
179 }
180 if (type == *fContext.fFloat3_Type || type == *fContext.fHalf3_Type) {
181 formatArgs->push_back(cppCode + ".fX");
182 formatArgs->push_back(cppCode + ".fY");
183 formatArgs->push_back(cppCode + ".fZ");
184 return type.name() + "(%f, %f, %f)";
185 }
186 if (type == *fContext.fFloat4_Type || type == *fContext.fHalf4_Type) {
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400187 switch (layout.fCType) {
188 case Layout::CType::kSkPMColor:
John Stiles47b4e222020-08-12 09:56:50 -0400189 formatArgs->push_back("SkGetPackedR32(" + cppCode + ") / 255.0");
190 formatArgs->push_back("SkGetPackedG32(" + cppCode + ") / 255.0");
191 formatArgs->push_back("SkGetPackedB32(" + cppCode + ") / 255.0");
192 formatArgs->push_back("SkGetPackedA32(" + cppCode + ") / 255.0");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400193 break;
Brian Osmanf28e55d2018-10-03 16:35:54 -0400194 case Layout::CType::kSkPMColor4f:
John Stiles47b4e222020-08-12 09:56:50 -0400195 formatArgs->push_back(cppCode + ".fR");
196 formatArgs->push_back(cppCode + ".fG");
197 formatArgs->push_back(cppCode + ".fB");
198 formatArgs->push_back(cppCode + ".fA");
Brian Osmanf28e55d2018-10-03 16:35:54 -0400199 break;
Mike Reedb26b4e72020-01-22 14:31:21 -0500200 case Layout::CType::kSkV4:
John Stiles47b4e222020-08-12 09:56:50 -0400201 formatArgs->push_back(cppCode + ".x");
202 formatArgs->push_back(cppCode + ".y");
203 formatArgs->push_back(cppCode + ".z");
204 formatArgs->push_back(cppCode + ".w");
Brian Salomoneca66b32019-06-01 11:18:15 -0400205 break;
John Stiles47b4e222020-08-12 09:56:50 -0400206 case Layout::CType::kSkRect:
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400207 case Layout::CType::kDefault:
John Stiles47b4e222020-08-12 09:56:50 -0400208 formatArgs->push_back(cppCode + ".left()");
209 formatArgs->push_back(cppCode + ".top()");
210 formatArgs->push_back(cppCode + ".right()");
211 formatArgs->push_back(cppCode + ".bottom()");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400212 break;
213 default:
214 SkASSERT(false);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400215 }
John Stiles47b4e222020-08-12 09:56:50 -0400216 return type.name() + "(%f, %f, %f, %f)";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400217 }
John Stiles47b4e222020-08-12 09:56:50 -0400218 if (type.kind() == Type::kMatrix_Kind) {
219 SkASSERT(type.componentType() == *fContext.fFloat_Type ||
220 type.componentType() == *fContext.fHalf_Type);
221
222 String format = type.name() + "(";
223 for (int c = 0; c < type.columns(); ++c) {
224 for (int r = 0; r < type.rows(); ++r) {
225 formatArgs->push_back(String::printf("%s.rc(%d, %d)", cppCode.c_str(), r, c));
226 format += "%f, ";
227 }
228 }
229
230 // Replace trailing ", " with ")".
231 format.pop_back();
232 format.back() = ')';
233 return format;
234 }
235 if (type.kind() == Type::kEnum_Kind) {
236 formatArgs->push_back("(int) " + cppCode);
237 return "%d";
238 }
239 if (type == *fContext.fInt4_Type ||
240 type == *fContext.fShort4_Type ||
241 type == *fContext.fByte4_Type) {
242 formatArgs->push_back(cppCode + ".left()");
243 formatArgs->push_back(cppCode + ".top()");
244 formatArgs->push_back(cppCode + ".right()");
245 formatArgs->push_back(cppCode + ".bottom()");
246 return type.name() + "(%d, %d, %d, %d)";
247 }
248
249 SkDEBUGFAILF("unsupported runtime value type '%s'\n", String(type.fName).c_str());
250 return "";
251}
252
253void CPPCodeGenerator::writeRuntimeValue(const Type& type, const Layout& layout,
254 const String& cppCode) {
255 this->write(this->formatRuntimeValue(type, layout, cppCode, &fFormatArgs));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400256}
257
258void CPPCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
259 if (is_private(var)) {
Ethan Nicholasd608c092017-10-26 09:30:08 -0400260 this->writeRuntimeValue(var.fType, var.fModifiers.fLayout, var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400261 } else {
262 this->writeExpression(value, kTopLevel_Precedence);
263 }
264}
265
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400266String CPPCodeGenerator::getSamplerHandle(const Variable& var) {
267 int samplerCount = 0;
Ethan Nicholas68990be2017-07-13 09:36:52 -0400268 for (const auto param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400269 if (&var == param) {
270 return "args.fTexSamplers[" + to_string(samplerCount) + "]";
271 }
272 if (param->fType.kind() == Type::kSampler_Kind) {
273 ++samplerCount;
274 }
275 }
276 ABORT("should have found sampler in parameters\n");
277}
278
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400279void CPPCodeGenerator::writeIntLiteral(const IntLiteral& i) {
280 this->write(to_string((int32_t) i.fValue));
281}
282
Ethan Nicholas82399462017-10-16 12:35:44 -0400283void CPPCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
284 if (fCPPMode) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400285 SkASSERT(swizzle.fComponents.size() == 1); // no support for multiple swizzle components yet
Ethan Nicholas82399462017-10-16 12:35:44 -0400286 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
287 switch (swizzle.fComponents[0]) {
288 case 0: this->write(".left()"); break;
289 case 1: this->write(".top()"); break;
290 case 2: this->write(".right()"); break;
291 case 3: this->write(".bottom()"); break;
292 }
293 } else {
294 INHERITED::writeSwizzle(swizzle);
295 }
296}
297
Ethan Nicholas762466e2017-06-29 10:03:38 -0400298void CPPCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400299 if (fCPPMode) {
300 this->write(ref.fVariable.fName);
301 return;
302 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400303 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400304 case SK_OUTCOLOR_BUILTIN:
305 this->write("%s");
306 fFormatArgs.push_back(String("args.fOutputColor"));
307 break;
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400308 case SK_MAIN_COORDS_BUILTIN:
309 this->write("%s");
310 fFormatArgs.push_back(String("args.fSampleCoord"));
311 fAccessSampleCoordsDirectly = true;
312 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -0400313 case SK_WIDTH_BUILTIN:
314 this->write("sk_Width");
315 break;
316 case SK_HEIGHT_BUILTIN:
317 this->write("sk_Height");
318 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400319 default:
320 if (ref.fVariable.fType.kind() == Type::kSampler_Kind) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400321 this->write("%s");
322 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerVariable(" +
Stephen Whited523a062019-06-19 13:12:46 -0400323 this->getSamplerHandle(ref.fVariable) + ")");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400324 return;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400325 }
326 if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag) {
327 this->write("%s");
328 String name = ref.fVariable.fName;
Brian Osman1cb41712017-10-19 12:54:52 -0400329 String var = String::printf("args.fUniformHandler->getUniformCStr(%sVar)",
330 HCodeGenerator::FieldName(name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400331 String code;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400332 if (ref.fVariable.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400333 code = String::printf("%sVar.isValid() ? %s : \"%s\"",
334 HCodeGenerator::FieldName(name.c_str()).c_str(),
335 var.c_str(),
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400336 default_value(ref.fVariable.fType).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400337 } else {
338 code = var;
339 }
340 fFormatArgs.push_back(code);
341 } else if (SectionAndParameterHelper::IsParameter(ref.fVariable)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700342 String name(ref.fVariable.fName);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400343 this->writeRuntimeValue(ref.fVariable.fType, ref.fVariable.fModifiers.fLayout,
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400344 String::printf("_outer.%s", name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400345 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700346 this->write(ref.fVariable.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400347 }
348 }
349}
350
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400351void CPPCodeGenerator::writeIfStatement(const IfStatement& s) {
352 if (s.fIsStatic) {
353 this->write("@");
354 }
355 INHERITED::writeIfStatement(s);
356}
357
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400358void CPPCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
359 if (fInMain) {
360 fErrors.error(s.fOffset, "fragmentProcessor main() may not contain return statements");
361 }
362 INHERITED::writeReturnStatement(s);
363}
364
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400365void CPPCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
366 if (s.fIsStatic) {
367 this->write("@");
368 }
369 INHERITED::writeSwitchStatement(s);
370}
371
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400372void CPPCodeGenerator::writeFieldAccess(const FieldAccess& access) {
373 if (access.fBase->fType.name() == "fragmentProcessor") {
374 // Special field access on fragment processors are converted into function calls on
375 // GrFragmentProcessor's getters.
376 if (access.fBase->fKind != Expression::kVariableReference_Kind) {
377 fErrors.error(access.fBase->fOffset, "fragmentProcessor must be a reference\n");
378 return;
379 }
380
381 const Type::Field& field = fContext.fFragmentProcessor_Type->fields()[access.fFieldIndex];
John Stiles3dc0da62020-08-19 17:48:31 -0400382 const Variable& var = access.fBase->as<VariableReference>().fVariable;
Brian Osman12c5d292020-07-13 16:11:35 -0400383 String cppAccess = String::printf("_outer.childProcessor(%d)->%s()",
384 this->getChildFPIndex(var),
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500385 String(field.fName).c_str());
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400386
387 if (fCPPMode) {
388 this->write(cppAccess.c_str());
389 } else {
390 writeRuntimeValue(*field.fType, Layout(), cppAccess);
391 }
392 return;
393 }
394 INHERITED::writeFieldAccess(access);
395}
396
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500397int CPPCodeGenerator::getChildFPIndex(const Variable& var) const {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400398 int index = 0;
399 bool found = false;
400 for (const auto& p : fProgram) {
401 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -0400402 const VarDeclarations& decls = p.as<VarDeclarations>();
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400403 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -0400404 const VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500405 if (decl.fVar == &var) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400406 found = true;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500407 } else if (decl.fVar->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400408 ++index;
409 }
410 }
411 }
412 if (found) {
413 break;
414 }
415 }
416 SkASSERT(found);
417 return index;
418}
419
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400420void CPPCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas13863662019-07-29 13:05:15 -0400421 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample" &&
422 c.fArguments[0]->fType.kind() != Type::Kind::kSampler_Kind) {
Leon Scroggins III982fff22020-07-31 14:09:06 -0400423 // Validity checks that are detected by function definition in sksl_fp.inc
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400424 SkASSERT(c.fArguments.size() >= 1 && c.fArguments.size() <= 3);
Florin Malita390f9bd2019-03-04 12:25:57 -0500425 SkASSERT("fragmentProcessor" == c.fArguments[0]->fType.name() ||
426 "fragmentProcessor?" == c.fArguments[0]->fType.name());
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400427
428 // Actually fail during compilation if arguments with valid types are
Ethan Nicholas13863662019-07-29 13:05:15 -0400429 // provided that are not variable references, since sample() is a
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400430 // special function that impacts code emission.
431 if (c.fArguments[0]->fKind != Expression::kVariableReference_Kind) {
432 fErrors.error(c.fArguments[0]->fOffset,
Ethan Nicholas13863662019-07-29 13:05:15 -0400433 "sample()'s fragmentProcessor argument must be a variable reference\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400434 return;
435 }
John Stiles3dc0da62020-08-19 17:48:31 -0400436 const Variable& child = c.fArguments[0]->as<VariableReference>().fVariable;
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400437
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400438 // Start a new extra emit code section so that the emitted child processor can depend on
439 // sksl variables defined in earlier sksl code.
440 this->newExtraEmitCodeBlock();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400441
Michael Ludwige88320b2020-06-24 09:04:56 -0400442 String inputColor;
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400443 if (c.fArguments.size() > 1 && c.fArguments[1]->fType.name() == "half4") {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400444 // Use the invokeChild() variant that accepts an input color, so convert the 2nd
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400445 // argument's expression into C++ code that produces sksl stored in an SkString.
Brian Osman12c5d292020-07-13 16:11:35 -0400446 String inputColorName = "_input" + to_string(c.fOffset);
John Stilesd060c9d2020-06-08 11:44:25 -0400447 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments[1], inputColorName));
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400448
Michael Ludwige88320b2020-06-24 09:04:56 -0400449 // invokeChild() needs a char* and a pre-pended comma
450 inputColor = ", " + inputColorName + ".c_str()";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400451 }
452
Michael Ludwige88320b2020-06-24 09:04:56 -0400453 String inputCoord;
454 String invokeFunction = "invokeChild";
455 if (c.fArguments.back()->fType.name() == "float2") {
456 // Invoking child with explicit coordinates at this call site
457 inputCoord = "_coords" + to_string(c.fOffset);
458 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), inputCoord));
459 inputCoord.append(".c_str()");
460 } else if (c.fArguments.back()->fType.name() == "float3x3") {
461 // Invoking child with a matrix, sampling relative to the input coords.
462 invokeFunction = "invokeChildWithMatrix";
Brian Osman1298bc42020-06-30 13:39:35 -0400463 SampleUsage usage = Analysis::GetSampleUsage(fProgram, child);
Michael Ludwige88320b2020-06-24 09:04:56 -0400464
Brian Osman1298bc42020-06-30 13:39:35 -0400465 if (!usage.hasUniformMatrix()) {
Michael Ludwige88320b2020-06-24 09:04:56 -0400466 inputCoord = "_matrix" + to_string(c.fOffset);
467 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), inputCoord));
468 inputCoord.append(".c_str()");
469 }
470 // else pass in the empty string to rely on invokeChildWithMatrix's automatic uniform
471 // resolution
472 }
473 if (!inputCoord.empty()) {
474 inputCoord = ", " + inputCoord;
475 }
476
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400477 // Write the output handling after the possible input handling
Ethan Nicholas13863662019-07-29 13:05:15 -0400478 String childName = "_sample" + to_string(c.fOffset);
Brian Osman12c5d292020-07-13 16:11:35 -0400479 String childIndexStr = to_string(this->getChildFPIndex(child));
480 addExtraEmitCodeLine("SkString " + childName + " = this->" + invokeFunction + "(" +
481 childIndexStr + inputColor + ", args" + inputCoord + ");");
John Stiles50819422020-06-18 13:00:38 -0400482
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000483 this->write("%s");
484 fFormatArgs.push_back(childName + ".c_str()");
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400485 return;
486 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400487 if (c.fFunction.fBuiltin) {
488 INHERITED::writeFunctionCall(c);
489 } else {
490 this->write("%s");
491 fFormatArgs.push_back((String(c.fFunction.fName) + "_name.c_str()").c_str());
492 this->write("(");
493 const char* separator = "";
494 for (const auto& arg : c.fArguments) {
495 this->write(separator);
496 separator = ", ";
497 this->writeExpression(*arg, kSequence_Precedence);
498 }
499 this->write(")");
500 }
Ethan Nicholas13863662019-07-29 13:05:15 -0400501 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample") {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400502 this->write(".%s");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400503 SkASSERT(c.fArguments.size() >= 1);
504 SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
John Stiles3dc0da62020-08-19 17:48:31 -0400505 String sampler = this->getSamplerHandle(c.fArguments[0]->as<VariableReference>().fVariable);
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400506 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
Greg Daniel369ee6b2019-12-02 15:30:02 -0500507 ").asString().c_str()");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400508 }
509}
510
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400511static const char* glsltype_string(const Context& context, const Type& type) {
512 if (type == *context.fFloat_Type) {
513 return "kFloat_GrSLType";
514 } else if (type == *context.fHalf_Type) {
515 return "kHalf_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400516 } else if (type == *context.fInt_Type) {
517 return "kInt_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400518 } else if (type == *context.fFloat2_Type) {
519 return "kFloat2_GrSLType";
520 } else if (type == *context.fHalf2_Type) {
521 return "kHalf2_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400522 } else if (type == *context.fInt2_Type) {
523 return "kInt2_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500524 } else if (type == *context.fFloat3_Type) {
525 return "kFloat3_GrSLType";
526 } else if (type == *context.fHalf3_Type) {
527 return "kHalf3_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400528 } else if (type == *context.fInt3_Type) {
529 return "kInt3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400530 } else if (type == *context.fFloat4_Type) {
531 return "kFloat4_GrSLType";
532 } else if (type == *context.fHalf4_Type) {
533 return "kHalf4_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400534 } else if (type == *context.fInt4_Type) {
535 return "kInt4_GrSLType";
Ethan Nicholas58430122020-04-14 09:54:02 -0400536 } else if (type == *context.fFloat2x2_Type) {
537 return "kFloat2x2_GrSLType";
538 } else if (type == *context.fHalf2x2_Type) {
539 return "kHalf2x2_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400540 } else if (type == *context.fFloat2x3_Type) {
541 return "kFloat2x3_GrSLType";
542 } else if (type == *context.fHalf2x3_Type) {
543 return "kHalf2x3_GrSLType";
544 } else if (type == *context.fFloat2x4_Type) {
545 return "kFloat2x4_GrSLType";
546 } else if (type == *context.fHalf2x4_Type) {
547 return "kHalf2x4_GrSLType";
548 } else if (type == *context.fFloat3x2_Type) {
549 return "kFloat3x2_GrSLType";
550 } else if (type == *context.fHalf3x2_Type) {
551 return "kHalf3x2_GrSLType";
Ethan Nicholas58430122020-04-14 09:54:02 -0400552 } else if (type == *context.fFloat3x3_Type) {
553 return "kFloat3x3_GrSLType";
554 } else if (type == *context.fHalf3x3_Type) {
555 return "kHalf3x3_GrSLType";
John Stiles0e8149c2020-08-18 12:23:40 -0400556 } else if (type == *context.fFloat3x4_Type) {
557 return "kFloat3x4_GrSLType";
558 } else if (type == *context.fHalf3x4_Type) {
559 return "kHalf3x4_GrSLType";
560 } else if (type == *context.fFloat4x2_Type) {
561 return "kFloat4x2_GrSLType";
562 } else if (type == *context.fHalf4x2_Type) {
563 return "kHalf4x2_GrSLType";
564 } else if (type == *context.fFloat4x3_Type) {
565 return "kFloat4x3_GrSLType";
566 } else if (type == *context.fHalf4x3_Type) {
567 return "kHalf4x3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400568 } else if (type == *context.fFloat4x4_Type) {
569 return "kFloat4x4_GrSLType";
570 } else if (type == *context.fHalf4x4_Type) {
571 return "kHalf4x4_GrSLType";
572 } else if (type == *context.fVoid_Type) {
573 return "kVoid_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500574 } else if (type.kind() == Type::kEnum_Kind) {
575 return "int";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400576 }
577 SkASSERT(false);
578 return nullptr;
579}
580
Ethan Nicholas762466e2017-06-29 10:03:38 -0400581void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400582 const FunctionDeclaration& decl = f.fDeclaration;
Brian Osman08f986d2020-05-13 17:06:46 -0400583 if (decl.fBuiltin) {
584 return;
585 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400586 fFunctionHeader = "";
587 OutputStream* oldOut = fOut;
588 StringStream buffer;
589 fOut = &buffer;
590 if (decl.fName == "main") {
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400591 fInMain = true;
John Stiles3dc0da62020-08-19 17:48:31 -0400592 for (const auto& s : f.fBody->as<Block>().fStatements) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400593 this->writeStatement(*s);
594 this->writeLine();
595 }
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400596 fInMain = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400597
598 fOut = oldOut;
599 this->write(fFunctionHeader);
600 this->write(buffer.str());
601 } else {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400602 this->addExtraEmitCodeLine("SkString " + decl.fName + "_name;");
603 String args = "const GrShaderVar " + decl.fName + "_args[] = { ";
604 const char* separator = "";
605 for (const auto& param : decl.fParameters) {
606 args += String(separator) + "GrShaderVar(\"" + param->fName + "\", " +
607 glsltype_string(fContext, param->fType) + ")";
608 separator = ", ";
609 }
610 args += "};";
611 this->addExtraEmitCodeLine(args.c_str());
John Stiles3dc0da62020-08-19 17:48:31 -0400612 for (const auto& s : f.fBody->as<Block>().fStatements) {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400613 this->writeStatement(*s);
614 this->writeLine();
615 }
616
617 fOut = oldOut;
618 String emit = "fragBuilder->emitFunction(";
619 emit += glsltype_string(fContext, decl.fReturnType);
620 emit += ", \"" + decl.fName + "\"";
621 emit += ", " + to_string((int64_t) decl.fParameters.size());
622 emit += ", " + decl.fName + "_args";
John Stiles50819422020-06-18 13:00:38 -0400623 emit += ",\nR\"SkSL(" + buffer.str() + ")SkSL\"";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400624 emit += ", &" + decl.fName + "_name);";
625 this->addExtraEmitCodeLine(emit.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400626 }
627}
628
629void CPPCodeGenerator::writeSetting(const Setting& s) {
Brian Osmanf265afd2020-08-04 13:23:36 -0400630 this->write(s.fName.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400631}
632
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400633bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400634 const Section* s = fSectionAndParameterHelper.getSection(name);
635 if (s) {
636 this->writef("%s%s", prefix, s->fText.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400637 return true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400638 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400639 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400640}
641
642void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
643 if (p.fKind == ProgramElement::kSection_Kind) {
644 return;
645 }
646 if (p.fKind == ProgramElement::kVar_Kind) {
John Stiles3dc0da62020-08-19 17:48:31 -0400647 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400648 if (!decls.fVars.size()) {
649 return;
650 }
John Stiles3dc0da62020-08-19 17:48:31 -0400651 const Variable& var = *decls.fVars[0]->as<VarDeclaration>().fVar;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400652 if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
653 -1 != var.fModifiers.fLayout.fBuiltin) {
654 return;
655 }
656 }
657 INHERITED::writeProgramElement(p);
658}
659
660void CPPCodeGenerator::addUniform(const Variable& var) {
661 if (!needs_uniform_var(var)) {
662 return;
663 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400664 if (var.fModifiers.fLayout.fWhen.fLength) {
665 this->writef(" if (%s) {\n ", String(var.fModifiers.fLayout.fWhen).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400666 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700667 String name(var.fName);
Ethan Nicholas7018bcf2020-08-20 15:57:22 -0400668 if (var.fType.kind() != Type::kArray_Kind) {
669 this->writef(" %sVar = args.fUniformHandler->addUniform(&_outer, "
670 "kFragment_GrShaderFlag, %s, \"%s\");\n",
671 HCodeGenerator::FieldName(name.c_str()).c_str(),
672 glsltype_string(fContext, var.fType),
673 name.c_str());
674 } else {
675 this->writef(" %sVar = args.fUniformHandler->addUniformArray(&_outer, "
676 "kFragment_GrShaderFlag, %s, \"%s\", %d);\n",
677 HCodeGenerator::FieldName(name.c_str()).c_str(),
678 glsltype_string(fContext, var.fType.componentType()),
679 name.c_str(),
680 var.fType.columns());
681 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400682 if (var.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400683 this->write(" }\n");
684 }
685}
686
Ethan Nicholascd700e92018-08-24 16:43:57 -0400687void CPPCodeGenerator::writeInputVars() {
688}
689
Ethan Nicholas762466e2017-06-29 10:03:38 -0400690void CPPCodeGenerator::writePrivateVars() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400691 for (const auto& p : fProgram) {
692 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -0400693 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400694 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -0400695 VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000696 if (is_private(*decl.fVar)) {
697 if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
698 fErrors.error(decl.fOffset,
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400699 "fragmentProcessor variables must be declared 'in'");
700 return;
701 }
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500702 this->writef("%s %s = %s;\n",
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000703 HCodeGenerator::FieldType(fContext, decl.fVar->fType,
704 decl.fVar->fModifiers.fLayout).c_str(),
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500705 String(decl.fVar->fName).c_str(),
706 default_value(*decl.fVar).c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400707 } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
708 // An auto-tracked uniform in variable, so add a field to hold onto the prior
709 // state. Note that tracked variables must be uniform in's and that is validated
710 // before writePrivateVars() is called.
711 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
712 SkASSERT(mapper && mapper->supportsTracking());
713
714 String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
715 // The member statement is different if the mapper reports a default value
716 if (mapper->defaultValue().size() > 0) {
717 this->writef("%s %sPrev = %s;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400718 Layout::CTypeToStr(mapper->ctype()), name.c_str(),
Michael Ludwiga4275592018-08-31 10:52:47 -0400719 mapper->defaultValue().c_str());
720 } else {
721 this->writef("%s %sPrev;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400722 Layout::CTypeToStr(mapper->ctype()), name.c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400723 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400724 }
725 }
726 }
727 }
728}
729
730void CPPCodeGenerator::writePrivateVarValues() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400731 for (const auto& p : fProgram) {
732 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -0400733 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400734 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -0400735 VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000736 if (is_private(*decl.fVar) && decl.fValue) {
737 this->writef("%s = ", String(decl.fVar->fName).c_str());
Ethan Nicholas82399462017-10-16 12:35:44 -0400738 fCPPMode = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000739 this->writeExpression(*decl.fValue, kAssignment_Precedence);
Ethan Nicholas82399462017-10-16 12:35:44 -0400740 fCPPMode = false;
741 this->write(";\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400742 }
743 }
744 }
745 }
746}
747
Ethan Nicholas82399462017-10-16 12:35:44 -0400748static bool is_accessible(const Variable& var) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500749 const Type& type = var.fType.nonnullable();
750 return Type::kSampler_Kind != type.kind() &&
751 Type::kOther_Kind != type.kind();
Ethan Nicholas82399462017-10-16 12:35:44 -0400752}
753
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400754void CPPCodeGenerator::newExtraEmitCodeBlock() {
755 // This should only be called when emitting SKSL for emitCode(), which can be detected if the
756 // cpp buffer is not null, and the cpp buffer is not the current output.
757 SkASSERT(fCPPBuffer && fCPPBuffer != fOut);
758
759 // Start a new block as an empty string
760 fExtraEmitCodeBlocks.push_back("");
761 // Mark its location in the output buffer, uses ${\d} for the token since ${} will not occur in
762 // valid sksl and makes detection trivial.
763 this->writef("${%zu}", fExtraEmitCodeBlocks.size() - 1);
764}
765
766void CPPCodeGenerator::addExtraEmitCodeLine(const String& toAppend) {
767 SkASSERT(fExtraEmitCodeBlocks.size() > 0);
768 String& currentBlock = fExtraEmitCodeBlocks[fExtraEmitCodeBlocks.size() - 1];
769 // Automatically add indentation and newline
770 currentBlock += " " + toAppend + "\n";
771}
772
773void CPPCodeGenerator::flushEmittedCode() {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400774 if (fCPPBuffer == nullptr) {
775 // Not actually within writeEmitCode() so nothing to flush
776 return;
777 }
778
779 StringStream* skslBuffer = static_cast<StringStream*>(fOut);
780
781 String sksl = skslBuffer->str();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400782 // Empty the accumulation buffer since its current contents are consumed.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400783 skslBuffer->reset();
784
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400785 // Switch to the cpp buffer
Michael Ludwigd0440192018-09-07 14:24:52 +0000786 fOut = fCPPBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400787
788 // Iterate through the sksl, keeping track of where the last statement ended (e.g. the latest
789 // encountered ';', '{', or '}'). If an extra emit code block token is encountered then the
790 // code from 0 to last statement end is sent to writeCodeAppend, the extra code block is
791 // appended to the cpp buffer, and then the sksl string is trimmed to start where the last
792 // statement left off (minus the encountered token).
793 size_t i = 0;
794 int flushPoint = -1;
795 int tokenStart = -1;
796 while (i < sksl.size()) {
797 if (tokenStart >= 0) {
798 // Looking for the end of the token
799 if (sksl[i] == '}') {
800 // Must append the sksl from 0 to flushPoint (inclusive) then the extra code
801 // accumulated in the block with index parsed from chars [tokenStart+2, i-1]
802 String toFlush = String(sksl.c_str(), flushPoint + 1);
803 // writeCodeAppend automatically removes the format args that it consumed, so
804 // fFormatArgs will be in a valid state for any future sksl
805 this->writeCodeAppend(toFlush);
806
807 int codeBlock = stoi(String(sksl.c_str() + tokenStart + 2, i - tokenStart - 2));
808 SkASSERT(codeBlock < (int) fExtraEmitCodeBlocks.size());
809 if (fExtraEmitCodeBlocks[codeBlock].size() > 0) {
810 this->write(fExtraEmitCodeBlocks[codeBlock].c_str());
811 }
812
813 // Now reset the sksl buffer to start after the flush point, but remove the token.
814 String compacted = String(sksl.c_str() + flushPoint + 1,
815 tokenStart - flushPoint - 1);
816 if (i < sksl.size() - 1) {
817 compacted += String(sksl.c_str() + i + 1, sksl.size() - i - 1);
818 }
819 sksl = compacted;
820
821 // And reset iteration
822 i = -1;
823 flushPoint = -1;
824 tokenStart = -1;
825 }
826 } else {
827 // Looking for the start of extra emit block tokens, and tracking when statements end
828 if (sksl[i] == ';' || sksl[i] == '{' || sksl[i] == '}') {
829 flushPoint = i;
830 } else if (i < sksl.size() - 1 && sksl[i] == '$' && sksl[i + 1] == '{') {
831 // found an extra emit code block token
832 tokenStart = i++;
833 }
834 }
835 i++;
Michael Ludwigd0440192018-09-07 14:24:52 +0000836 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400837
838 // Once we've gone through the sksl string to this point, there are no remaining extra emit
839 // code blocks to interleave, so append the remainder as usual.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400840 this->writeCodeAppend(sksl);
841
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400842 // After appending, switch back to the emptied sksl buffer and reset the extra code blocks
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400843 fOut = skslBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400844 fExtraEmitCodeBlocks.clear();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400845}
846
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400847void CPPCodeGenerator::writeCodeAppend(const String& code) {
John Stiles50819422020-06-18 13:00:38 -0400848 if (!code.empty()) {
849 // Count % format specifiers.
850 size_t argCount = 0;
851 for (size_t index = 0; index < code.size(); ++index) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400852 if ('%' == code[index]) {
John Stiles50819422020-06-18 13:00:38 -0400853 if (index == code.size() - 1) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400854 break;
855 }
856 if (code[index + 1] != '%') {
857 ++argCount;
858 }
859 }
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400860 }
John Stiles50819422020-06-18 13:00:38 -0400861
862 // Emit the code string.
863 this->writef(" fragBuilder->codeAppendf(\n"
864 "R\"SkSL(%s)SkSL\"\n", code.c_str());
865 for (size_t i = 0; i < argCount; ++i) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400866 this->writef(", %s", fFormatArgs[i].c_str());
867 }
868 this->write(");\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400869
John Stiles50819422020-06-18 13:00:38 -0400870 // argCount is equal to the number of fFormatArgs that were consumed, so they should be
871 // removed from the list.
872 if (argCount > 0) {
873 fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argCount);
874 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400875 }
876}
877
878String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
879 const String& cppVar) {
880 // To do this conversion, we temporarily switch the sksl output stream
881 // to an empty stringstream and reset the format args to empty.
882 OutputStream* oldSKSL = fOut;
883 StringStream exprBuffer;
884 fOut = &exprBuffer;
885
886 std::vector<String> oldArgs(fFormatArgs);
887 fFormatArgs.clear();
888
889 // Convert the argument expression into a format string and args
890 this->writeExpression(e, Precedence::kTopLevel_Precedence);
891 std::vector<String> newArgs(fFormatArgs);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400892 String expr = exprBuffer.str();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400893
894 // After generating, restore the original output stream and format args
895 fFormatArgs = oldArgs;
896 fOut = oldSKSL;
897
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400898 // The sksl written to exprBuffer is not processed by flushEmittedCode(), so any extra emit code
899 // block tokens won't get handled. So we need to strip them from the expression and stick them
900 // to the end of the original sksl stream.
901 String exprFormat = "";
902 int tokenStart = -1;
903 for (size_t i = 0; i < expr.size(); i++) {
904 if (tokenStart >= 0) {
905 if (expr[i] == '}') {
906 // End of the token, so append the token to fOut
907 fOut->write(expr.c_str() + tokenStart, i - tokenStart + 1);
908 tokenStart = -1;
909 }
910 } else {
911 if (i < expr.size() - 1 && expr[i] == '$' && expr[i + 1] == '{') {
912 tokenStart = i++;
913 } else {
914 exprFormat += expr[i];
915 }
916 }
917 }
918
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400919 // Now build the final C++ code snippet from the format string and args
920 String cppExpr;
John Stiles50819422020-06-18 13:00:38 -0400921 if (newArgs.empty()) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400922 // This was a static expression, so we can simplify the input
923 // color declaration in the emitted code to just a static string
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400924 cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");";
John Stiles50819422020-06-18 13:00:38 -0400925 } else if (newArgs.size() == 1 && exprFormat == "%s") {
926 // If the format expression is simply "%s", we can avoid an expensive call to printf.
927 // This happens fairly often in codegen so it is worth simplifying.
928 cppExpr = "SkString " + cppVar + "(" + newArgs[0] + ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400929 } else {
930 // String formatting must occur dynamically, so have the C++ declaration
931 // use SkStringPrintf with the format args that were accumulated
932 // when the expression was written.
933 cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
934 for (size_t i = 0; i < newArgs.size(); i++) {
935 cppExpr += ", " + newArgs[i];
936 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400937 cppExpr += ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400938 }
939 return cppExpr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400940}
941
Ethan Nicholas762466e2017-06-29 10:03:38 -0400942bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
943 this->write(" void emitCode(EmitArgs& args) override {\n"
944 " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
945 this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
946 " (void) _outer;\n",
947 fFullName.c_str(), fFullName.c_str());
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400948 for (const auto& p : fProgram) {
949 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -0400950 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400951 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -0400952 VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000953 String nameString(decl.fVar->fName);
Ethan Nicholas82399462017-10-16 12:35:44 -0400954 const char* name = nameString.c_str();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000955 if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
956 is_accessible(*decl.fVar)) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400957 this->writef(" auto %s = _outer.%s;\n"
Ethan Nicholas82399462017-10-16 12:35:44 -0400958 " (void) %s;\n",
959 name, name, name);
960 }
961 }
962 }
963 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400964 this->writePrivateVarValues();
965 for (const auto u : uniforms) {
966 this->addUniform(*u);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400967 }
John Stiles02b11282020-08-10 15:25:24 -0400968 this->writeSection(kEmitCodeSection);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400969
970 // Save original buffer as the CPP buffer for flushEmittedCode()
971 fCPPBuffer = fOut;
972 StringStream skslBuffer;
973 fOut = &skslBuffer;
974
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400975 this->newExtraEmitCodeBlock();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400976 bool result = INHERITED::generateCode();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400977 this->flushEmittedCode();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400978
979 // Then restore the original CPP buffer and close the function
980 fOut = fCPPBuffer;
981 fCPPBuffer = nullptr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400982 this->write(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400983 return result;
984}
985
986void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
987 const char* fullName = fFullName.c_str();
John Stiles02b11282020-08-10 15:25:24 -0400988 const Section* section = fSectionAndParameterHelper.getSection(kSetDataSection);
Ethan Nicholas68990be2017-07-13 09:36:52 -0400989 const char* pdman = section ? section->fArgument.c_str() : "pdman";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400990 this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
991 "const GrFragmentProcessor& _proc) override {\n",
992 pdman);
993 bool wroteProcessor = false;
John Stiles06f3d082020-06-04 11:07:21 -0400994 for (const Variable* u : uniforms) {
Michael Ludwiga4275592018-08-31 10:52:47 -0400995 if (is_uniform_in(*u)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400996 if (!wroteProcessor) {
997 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
998 wroteProcessor = true;
999 this->writef(" {\n");
1000 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001001
1002 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
1003 SkASSERT(mapper);
1004
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001005 String nameString(u->fName);
1006 const char* name = nameString.c_str();
Michael Ludwiga4275592018-08-31 10:52:47 -04001007
1008 // Switches for setData behavior in the generated code
1009 bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
1010 bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
1011 bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
1012
1013 String uniformName = HCodeGenerator::FieldName(name) + "Var";
1014
1015 String indent = " "; // 8 by default, 12 when nested for conditional uniforms
1016 if (conditionalUniform) {
1017 // Add a pre-check to make sure the uniform was emitted
1018 // before trying to send any data to the GPU
1019 this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
1020 indent += " ";
1021 }
1022
1023 String valueVar = "";
1024 if (needsValueDeclaration) {
1025 valueVar.appendf("%sValue", name);
1026 // Use AccessType since that will match the return type of _outer's public API.
1027 String valueType = HCodeGenerator::AccessType(fContext, u->fType,
1028 u->fModifiers.fLayout);
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001029 this->writef("%s%s %s = _outer.%s;\n",
Michael Ludwiga4275592018-08-31 10:52:47 -04001030 indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001031 } else {
Michael Ludwiga4275592018-08-31 10:52:47 -04001032 // Not tracked and the mapper only needs to use the value once
1033 // so send it a safe expression instead of the variable name
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001034 valueVar.appendf("(_outer.%s)", name);
Michael Ludwiga4275592018-08-31 10:52:47 -04001035 }
1036
1037 if (isTracked) {
1038 SkASSERT(mapper->supportsTracking());
1039
1040 String prevVar = HCodeGenerator::FieldName(name) + "Prev";
1041 this->writef("%sif (%s) {\n"
1042 "%s %s;\n"
1043 "%s %s;\n"
1044 "%s}\n", indent.c_str(),
1045 mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
1046 mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
1047 mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
1048 } else {
1049 this->writef("%s%s;\n", indent.c_str(),
1050 mapper->setUniform(pdman, uniformName, valueVar).c_str());
1051 }
1052
1053 if (conditionalUniform) {
1054 // Close the earlier precheck block
1055 this->writef(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001056 }
1057 }
1058 }
1059 if (wroteProcessor) {
1060 this->writef(" }\n");
1061 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001062 if (section) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001063 int samplerIndex = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001064 for (const auto& p : fProgram) {
1065 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001066 const VarDeclarations& decls = p.as<VarDeclarations>();
John Stiles06f3d082020-06-04 11:07:21 -04001067 for (const std::unique_ptr<Statement>& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001068 const VarDeclaration& decl = raw->as<VarDeclaration>();
John Stiles06f3d082020-06-04 11:07:21 -04001069 const Variable& variable = *decl.fVar;
1070 String nameString(variable.fName);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001071 const char* name = nameString.c_str();
John Stiles06f3d082020-06-04 11:07:21 -04001072 if (variable.fType.kind() == Type::kSampler_Kind) {
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001073 this->writef(" const GrSurfaceProxyView& %sView = "
1074 "_outer.textureSampler(%d).view();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001075 name, samplerIndex);
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001076 this->writef(" GrTexture& %s = *%sView.proxy()->peekTexture();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001077 name, name);
1078 this->writef(" (void) %s;\n", name);
1079 ++samplerIndex;
John Stiles06f3d082020-06-04 11:07:21 -04001080 } else if (needs_uniform_var(variable)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001081 this->writef(" UniformHandle& %s = %sVar;\n"
1082 " (void) %s;\n",
1083 name, HCodeGenerator::FieldName(name).c_str(), name);
John Stiles06f3d082020-06-04 11:07:21 -04001084 } else if (SectionAndParameterHelper::IsParameter(variable) &&
1085 variable.fType != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001086 if (!wroteProcessor) {
1087 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
1088 fullName);
1089 wroteProcessor = true;
1090 }
John Stiles06f3d082020-06-04 11:07:21 -04001091
1092 if (variable.fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
1093 this->writef(" auto %s = _outer.%s;\n"
1094 " (void) %s;\n",
1095 name, name, name);
1096 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001097 }
1098 }
1099 }
1100 }
John Stiles02b11282020-08-10 15:25:24 -04001101 this->writeSection(kSetDataSection);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001102 }
1103 this->write(" }\n");
1104}
1105
Brian Salomonf7dcd762018-07-30 14:48:15 -04001106void CPPCodeGenerator::writeOnTextureSampler() {
1107 bool foundSampler = false;
1108 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1109 if (param->fType.kind() == Type::kSampler_Kind) {
1110 if (!foundSampler) {
1111 this->writef(
1112 "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
1113 "index) const {\n",
1114 fFullName.c_str());
1115 this->writef(" return IthTextureSampler(index, %s",
1116 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1117 foundSampler = true;
1118 } else {
1119 this->writef(", %s",
1120 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1121 }
1122 }
1123 }
1124 if (foundSampler) {
1125 this->write(");\n}\n");
1126 }
1127}
1128
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001129void CPPCodeGenerator::writeClone() {
John Stiles02b11282020-08-10 15:25:24 -04001130 if (!this->writeSection(kCloneSection)) {
1131 if (fSectionAndParameterHelper.getSection(kFieldsSection)) {
John Stiles47b4e222020-08-12 09:56:50 -04001132 fErrors.error(/*offset=*/0, "fragment processors with custom @fields must also have a "
1133 "custom @clone");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001134 }
1135 this->writef("%s::%s(const %s& src)\n"
Ethan Nicholasabff9562017-10-09 10:54:08 -04001136 ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
1137 fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
John Stiles06f3d082020-06-04 11:07:21 -04001138 for (const Variable* param : fSectionAndParameterHelper.getParameters()) {
Robert Phillipsbce7d862019-02-21 22:53:57 +00001139 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
John Stiles88183902020-06-10 16:40:38 -04001140 if (param->fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001141 this->writef("\n, %s(src.%s)",
1142 fieldName.c_str(),
1143 fieldName.c_str());
1144 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001145 }
Ethan Nicholasabff9562017-10-09 10:54:08 -04001146 this->writef(" {\n");
Brian Osman12c5d292020-07-13 16:11:35 -04001147 this->writef(" this->cloneAndRegisterAllChildProcessors(src);\n");
Brian Salomonf7dcd762018-07-30 14:48:15 -04001148 int samplerCount = 0;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001149 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1150 if (param->fType.kind() == Type::kSampler_Kind) {
Brian Salomonf7dcd762018-07-30 14:48:15 -04001151 ++samplerCount;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001152 }
1153 }
Brian Salomonf7dcd762018-07-30 14:48:15 -04001154 if (samplerCount) {
1155 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
1156 }
Michael Ludwige88320b2020-06-24 09:04:56 -04001157 if (fAccessSampleCoordsDirectly) {
1158 this->writef(" this->setUsesSampleCoordsDirectly();\n");
1159 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001160 this->write("}\n");
Brian Salomonaff329b2017-08-11 09:40:37 -04001161 this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
1162 fFullName.c_str());
John Stilesfbd050b2020-08-03 13:21:46 -04001163 this->writef(" return std::make_unique<%s>(*this);\n",
Brian Salomonaff329b2017-08-11 09:40:37 -04001164 fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001165 this->write("}\n");
1166 }
1167}
1168
John Stiles47b4e222020-08-12 09:56:50 -04001169void CPPCodeGenerator::writeDumpInfo() {
John Stiles8d9bf642020-08-12 15:07:45 -04001170 this->writef("#if GR_TEST_UTILS\n"
John Stilescab58862020-08-12 15:47:06 -04001171 "SkString %s::onDumpInfo() const {\n", fFullName.c_str());
John Stiles47b4e222020-08-12 09:56:50 -04001172
1173 if (!this->writeSection(kDumpInfoSection)) {
1174 if (fSectionAndParameterHelper.getSection(kFieldsSection)) {
1175 fErrors.error(/*offset=*/0, "fragment processors with custom @fields must also have a "
1176 "custom @dumpInfo");
1177 }
1178
John Stiles47b4e222020-08-12 09:56:50 -04001179 String formatString;
1180 std::vector<String> argumentList;
1181
1182 for (const Variable* param : fSectionAndParameterHelper.getParameters()) {
1183 // dumpInfo() doesn't need to log child FPs.
1184 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
1185 continue;
1186 }
1187
1188 // Add this field onto the format string and argument list.
1189 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
1190 String runtimeValue = this->formatRuntimeValue(param->fType, param->fModifiers.fLayout,
1191 param->fName, &argumentList);
1192 formatString.appendf("%s%s=%s",
1193 formatString.empty() ? "" : ", ",
1194 fieldName.c_str(),
1195 runtimeValue.c_str());
1196 }
1197
John Stiles47b4e222020-08-12 09:56:50 -04001198 if (!formatString.empty()) {
John Stilescab58862020-08-12 15:47:06 -04001199 // Emit the finished format string and associated arguments.
1200 this->writef(" return SkStringPrintf(\"(%s)\"", formatString.c_str());
John Stiles47b4e222020-08-12 09:56:50 -04001201
John Stilescab58862020-08-12 15:47:06 -04001202 for (const String& argument : argumentList) {
1203 this->writef(", %s", argument.c_str());
1204 }
John Stiles47b4e222020-08-12 09:56:50 -04001205
John Stilescab58862020-08-12 15:47:06 -04001206 this->write(");");
1207 } else {
1208 // No fields to dump at all; just return an empty string.
1209 this->write(" return SkString();");
1210 }
John Stiles47b4e222020-08-12 09:56:50 -04001211 }
1212
John Stilescab58862020-08-12 15:47:06 -04001213 this->write("\n"
1214 "}\n"
John Stiles47b4e222020-08-12 09:56:50 -04001215 "#endif\n");
1216}
1217
Ethan Nicholas762466e2017-06-29 10:03:38 -04001218void CPPCodeGenerator::writeTest() {
John Stiles02b11282020-08-10 15:25:24 -04001219 const Section* test = fSectionAndParameterHelper.getSection(kTestCodeSection);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001220 if (test) {
Brian Salomonaff329b2017-08-11 09:40:37 -04001221 this->writef(
1222 "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
1223 "#if GR_TEST_UTILS\n"
1224 "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
1225 fFullName.c_str(),
1226 fFullName.c_str(),
1227 test->fArgument.c_str());
John Stiles02b11282020-08-10 15:25:24 -04001228 this->writeSection(kTestCodeSection);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001229 this->write("}\n"
1230 "#endif\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001231 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001232}
1233
1234void CPPCodeGenerator::writeGetKey() {
1235 this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
1236 "GrProcessorKeyBuilder* b) const {\n",
1237 fFullName.c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001238 for (const auto& p : fProgram) {
1239 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001240 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholascab767f2019-07-01 13:32:07 -04001241 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001242 const VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholascab767f2019-07-01 13:32:07 -04001243 const Variable& var = *decl.fVar;
1244 String nameString(var.fName);
1245 const char* name = nameString.c_str();
1246 if (var.fModifiers.fLayout.fKey != Layout::kNo_Key &&
1247 (var.fModifiers.fFlags & Modifiers::kUniform_Flag)) {
1248 fErrors.error(var.fOffset,
1249 "layout(key) may not be specified on uniforms");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001250 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001251 switch (var.fModifiers.fLayout.fKey) {
1252 case Layout::kKey_Key:
1253 if (is_private(var)) {
1254 this->writef("%s %s =",
1255 HCodeGenerator::FieldType(fContext, var.fType,
1256 var.fModifiers.fLayout).c_str(),
1257 String(var.fName).c_str());
1258 if (decl.fValue) {
1259 fCPPMode = true;
1260 this->writeExpression(*decl.fValue, kAssignment_Precedence);
1261 fCPPMode = false;
1262 } else {
1263 this->writef("%s", default_value(var).c_str());
1264 }
1265 this->write(";\n");
1266 }
1267 if (var.fModifiers.fLayout.fWhen.fLength) {
1268 this->writef("if (%s) {", String(var.fModifiers.fLayout.fWhen).c_str());
1269 }
John Stilesb3038f82020-07-27 17:33:25 -04001270 if (var.fType == *fContext.fHalf4_Type) {
Ethan Nicholascab767f2019-07-01 13:32:07 -04001271 this->writef(" uint16_t red = SkFloatToHalf(%s.fR);\n",
1272 HCodeGenerator::FieldName(name).c_str());
1273 this->writef(" uint16_t green = SkFloatToHalf(%s.fG);\n",
1274 HCodeGenerator::FieldName(name).c_str());
1275 this->writef(" uint16_t blue = SkFloatToHalf(%s.fB);\n",
1276 HCodeGenerator::FieldName(name).c_str());
1277 this->writef(" uint16_t alpha = SkFloatToHalf(%s.fA);\n",
1278 HCodeGenerator::FieldName(name).c_str());
1279 this->write(" b->add32(((uint32_t)red << 16) | green);\n");
1280 this->write(" b->add32(((uint32_t)blue << 16) | alpha);\n");
John Stiles45f5b032020-07-27 17:31:29 -04001281 } else if (var.fType == *fContext.fHalf_Type ||
1282 var.fType == *fContext.fFloat_Type) {
1283 this->writef(" b->add32(sk_bit_cast<uint32_t>(%s));\n",
Ethan Nicholascab767f2019-07-01 13:32:07 -04001284 HCodeGenerator::FieldName(name).c_str());
John Stiles45f5b032020-07-27 17:31:29 -04001285 } else if (var.fType.isInteger() || var.fType == *fContext.fBool_Type ||
1286 var.fType.kind() == Type::kEnum_Kind) {
1287 this->writef(" b->add32((uint32_t) %s);\n",
1288 HCodeGenerator::FieldName(name).c_str());
1289 } else {
1290 ABORT("NOT YET IMPLEMENTED: automatic key handling for %s\n",
1291 var.fType.displayName().c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001292 }
1293 if (var.fModifiers.fLayout.fWhen.fLength) {
1294 this->write("}");
1295 }
1296 break;
1297 case Layout::kIdentity_Key:
1298 if (var.fType.kind() != Type::kMatrix_Kind) {
1299 fErrors.error(var.fOffset,
1300 "layout(key=identity) requires matrix type");
1301 }
1302 this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
1303 HCodeGenerator::FieldName(name).c_str());
1304 break;
1305 case Layout::kNo_Key:
1306 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001307 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001308 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001309 }
1310 }
1311 this->write("}\n");
1312}
1313
1314bool CPPCodeGenerator::generateCode() {
1315 std::vector<const Variable*> uniforms;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001316 for (const auto& p : fProgram) {
1317 if (ProgramElement::kVar_Kind == p.fKind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001318 const VarDeclarations& decls = p.as<VarDeclarations>();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001319 for (const auto& raw : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001320 VarDeclaration& decl = raw->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001321 if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1322 decl.fVar->fType.kind() != Type::kSampler_Kind) {
1323 uniforms.push_back(decl.fVar);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001324 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001325
1326 if (is_uniform_in(*decl.fVar)) {
1327 // Validate the "uniform in" declarations to make sure they are fully supported,
1328 // instead of generating surprising C++
1329 const UniformCTypeMapper* mapper =
1330 UniformCTypeMapper::Get(fContext, *decl.fVar);
1331 if (mapper == nullptr) {
1332 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1333 + "'s type is not supported for use as a 'uniform in'");
1334 return false;
1335 }
1336 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1337 if (!mapper->supportsTracking()) {
1338 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1339 + "'s type does not support state tracking");
1340 return false;
1341 }
1342 }
1343
1344 } else {
1345 // If it's not a uniform_in, it's an error to be tracked
1346 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1347 fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
1348 return false;
1349 }
1350 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001351 }
1352 }
1353 }
1354 const char* baseName = fName.c_str();
1355 const char* fullName = fFullName.c_str();
Ethan Nicholas130fb3f2018-02-01 12:14:34 -05001356 this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001357 this->writef(kFragmentProcessorHeader, fullName);
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001358 this->writef("#include \"%s.h\"\n\n", fullName);
John Stiles02b11282020-08-10 15:25:24 -04001359 this->writeSection(kCppSection);
John Stiles45f5b032020-07-27 17:31:29 -04001360 this->writef("#include \"src/core/SkUtils.h\"\n"
1361 "#include \"src/gpu/GrTexture.h\"\n"
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001362 "#include \"src/gpu/glsl/GrGLSLFragmentProcessor.h\"\n"
1363 "#include \"src/gpu/glsl/GrGLSLFragmentShaderBuilder.h\"\n"
1364 "#include \"src/gpu/glsl/GrGLSLProgramBuilder.h\"\n"
1365 "#include \"src/sksl/SkSLCPP.h\"\n"
1366 "#include \"src/sksl/SkSLUtil.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001367 "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
1368 "public:\n"
1369 " GrGLSL%s() {}\n",
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001370 baseName, baseName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001371 bool result = this->writeEmitCode(uniforms);
1372 this->write("private:\n");
1373 this->writeSetData(uniforms);
1374 this->writePrivateVars();
1375 for (const auto& u : uniforms) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001376 if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001377 this->writef(" UniformHandle %sVar;\n",
1378 HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001379 }
1380 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001381 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001382 if (needs_uniform_var(*param)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001383 this->writef(" UniformHandle %sVar;\n",
1384 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001385 }
1386 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001387 this->writef("};\n"
1388 "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
1389 " return new GrGLSL%s();\n"
1390 "}\n",
1391 fullName, baseName);
1392 this->writeGetKey();
1393 this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
1394 " const %s& that = other.cast<%s>();\n"
1395 " (void) that;\n",
1396 fullName, fullName, fullName);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001397 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001398 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001399 continue;
1400 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001401 String nameString(param->fName);
1402 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001403 this->writef(" if (%s != that.%s) return false;\n",
1404 HCodeGenerator::FieldName(name).c_str(),
1405 HCodeGenerator::FieldName(name).c_str());
1406 }
1407 this->write(" return true;\n"
1408 "}\n");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001409 this->writeClone();
John Stiles47b4e222020-08-12 09:56:50 -04001410 this->writeDumpInfo();
Brian Salomonf7dcd762018-07-30 14:48:15 -04001411 this->writeOnTextureSampler();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001412 this->writeTest();
John Stiles02b11282020-08-10 15:25:24 -04001413 this->writeSection(kCppEndSection);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001414
Ethan Nicholas762466e2017-06-29 10:03:38 -04001415 result &= 0 == fErrors.errorCount();
1416 return result;
1417}
1418
John Stilesa6841be2020-08-06 14:11:56 -04001419} // namespace SkSL
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001420
1421#endif // defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)