blob: a4d2e3b590473241de63575156695f2827b33e70 [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/SkSLCPPUniformCTypes.h"
11#include "src/sksl/SkSLCompiler.h"
12#include "src/sksl/SkSLHCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040013
Michael Ludwig92e4c7f2018-08-30 16:08:18 -040014#include <algorithm>
15
Ethan Nicholas762466e2017-06-29 10:03:38 -040016namespace SkSL {
17
18static bool needs_uniform_var(const Variable& var) {
Ethan Nicholas5f9836e2017-12-20 15:16:33 -050019 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
20 var.fType.kind() != Type::kSampler_Kind;
Ethan Nicholas762466e2017-06-29 10:03:38 -040021}
22
23CPPCodeGenerator::CPPCodeGenerator(const Context* context, const Program* program,
24 ErrorReporter* errors, String name, OutputStream* out)
25: INHERITED(context, program, errors, out)
26, fName(std::move(name))
27, fFullName(String::printf("Gr%s", fName.c_str()))
Ethan Nicholasd4efe682019-08-29 16:10:13 -040028, fSectionAndParameterHelper(program, *errors) {
Ethan Nicholas762466e2017-06-29 10:03:38 -040029 fLineEnding = "\\n";
Ethan Nicholas13863662019-07-29 13:05:15 -040030 fTextureFunctionOverride = "sample";
Ethan Nicholas762466e2017-06-29 10:03:38 -040031}
32
33void CPPCodeGenerator::writef(const char* s, va_list va) {
34 static constexpr int BUFFER_SIZE = 1024;
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040035 va_list copy;
36 va_copy(copy, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040037 char buffer[BUFFER_SIZE];
38 int length = vsnprintf(buffer, BUFFER_SIZE, s, va);
39 if (length < BUFFER_SIZE) {
40 fOut->write(buffer, length);
41 } else {
42 std::unique_ptr<char[]> heap(new char[length + 1]);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040043 vsprintf(heap.get(), s, copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040044 fOut->write(heap.get(), length);
45 }
z102.zhangd74f2c82018-08-10 09:08:47 +080046 va_end(copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040047}
48
49void CPPCodeGenerator::writef(const char* s, ...) {
50 va_list va;
51 va_start(va, s);
52 this->writef(s, va);
53 va_end(va);
54}
55
56void CPPCodeGenerator::writeHeader() {
57}
58
Ethan Nicholasf7b88202017-09-18 14:10:39 -040059bool CPPCodeGenerator::usesPrecisionModifiers() const {
60 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -040061}
62
Ethan Nicholasf7b88202017-09-18 14:10:39 -040063String CPPCodeGenerator::getTypeName(const Type& type) {
64 return type.name();
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040065}
Ethan Nicholasf7b88202017-09-18 14:10:39 -040066
Ethan Nicholas762466e2017-06-29 10:03:38 -040067void CPPCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
68 Precedence parentPrecedence) {
69 if (b.fOperator == Token::PERCENT) {
70 // need to use "%%" instead of "%" b/c the code will be inside of a printf
71 Precedence precedence = GetBinaryPrecedence(b.fOperator);
72 if (precedence >= parentPrecedence) {
73 this->write("(");
74 }
75 this->writeExpression(*b.fLeft, precedence);
76 this->write(" %% ");
77 this->writeExpression(*b.fRight, precedence);
78 if (precedence >= parentPrecedence) {
79 this->write(")");
80 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050081 } else if (b.fLeft->fKind == Expression::kNullLiteral_Kind ||
82 b.fRight->fKind == Expression::kNullLiteral_Kind) {
83 const Variable* var;
84 if (b.fLeft->fKind != Expression::kNullLiteral_Kind) {
85 SkASSERT(b.fLeft->fKind == Expression::kVariableReference_Kind);
86 var = &((VariableReference&) *b.fLeft).fVariable;
87 } else {
88 SkASSERT(b.fRight->fKind == Expression::kVariableReference_Kind);
89 var = &((VariableReference&) *b.fRight).fVariable;
90 }
91 SkASSERT(var->fType.kind() == Type::kNullable_Kind &&
92 var->fType.componentType() == *fContext.fFragmentProcessor_Type);
93 this->write("%s");
94 const char* op;
95 switch (b.fOperator) {
96 case Token::EQEQ:
97 op = "<";
98 break;
99 case Token::NEQ:
100 op = ">=";
101 break;
102 default:
103 SkASSERT(false);
104 }
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400105 fFormatArgs.push_back("_outer." + String(var->fName) + "_index " + op + " 0 ? \"true\" "
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500106 ": \"false\"");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400107 } else {
108 INHERITED::writeBinaryExpression(b, parentPrecedence);
109 }
110}
111
112void CPPCodeGenerator::writeIndexExpression(const IndexExpression& i) {
113 const Expression& base = *i.fBase;
114 if (base.fKind == Expression::kVariableReference_Kind) {
115 int builtin = ((VariableReference&) base).fVariable.fModifiers.fLayout.fBuiltin;
116 if (SK_TRANSFORMEDCOORDS2D_BUILTIN == builtin) {
117 this->write("%s");
118 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700119 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400120 "index into sk_TransformedCoords2D must be an integer literal");
121 return;
122 }
123 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
124 String name = "sk_TransformedCoords2D_" + to_string(index);
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400125 fFormatArgs.push_back("_outer.computeLocalCoordsInVertexShader() ? " + name +
126 ".c_str() : \"_coords\"");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400127 if (fWrittenTransformedCoords.find(index) == fWrittenTransformedCoords.end()) {
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400128 addExtraEmitCodeLine("SkString " + name +
129 " = fragBuilder->ensureCoords2D(args.fTransformedCoords[" +
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400130 to_string(index) + "].fVaryingPoint);");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400131 fWrittenTransformedCoords.insert(index);
132 }
133 return;
134 } else if (SK_TEXTURESAMPLERS_BUILTIN == builtin) {
135 this->write("%s");
136 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700137 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400138 "index into sk_TextureSamplers must be an integer literal");
139 return;
140 }
141 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
142 fFormatArgs.push_back(" fragBuilder->getProgramBuilder()->samplerVariable("
Stephen Whited523a062019-06-19 13:12:46 -0400143 "args.fTexSamplers[" + to_string(index) + "])");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400144 return;
145 }
146 }
147 INHERITED::writeIndexExpression(i);
148}
149
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400150static String default_value(const Type& type) {
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500151 if (type.fName == "bool") {
152 return "false";
153 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400154 switch (type.kind()) {
155 case Type::kScalar_Kind: return "0";
156 case Type::kVector_Kind: return type.name() + "(0)";
157 case Type::kMatrix_Kind: return type.name() + "(1)";
158 default: ABORT("unsupported default_value type\n");
159 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400160}
161
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500162static String default_value(const Variable& var) {
Brian Osman495993a2018-10-16 15:45:55 -0400163 if (var.fModifiers.fLayout.fCType == SkSL::Layout::CType::kSkPMColor4f) {
Brian Osmanf28e55d2018-10-03 16:35:54 -0400164 return "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}";
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500165 }
166 return default_value(var.fType);
167}
168
Ethan Nicholas762466e2017-06-29 10:03:38 -0400169static bool is_private(const Variable& var) {
170 return !(var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
171 !(var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
172 var.fStorage == Variable::kGlobal_Storage &&
173 var.fModifiers.fLayout.fBuiltin == -1;
174}
175
Michael Ludwiga4275592018-08-31 10:52:47 -0400176static bool is_uniform_in(const Variable& var) {
177 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
178 (var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
179 var.fType.kind() != Type::kSampler_Kind;
180}
181
Ethan Nicholasd608c092017-10-26 09:30:08 -0400182void CPPCodeGenerator::writeRuntimeValue(const Type& type, const Layout& layout,
183 const String& cppCode) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400184 if (type.isFloat()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400185 this->write("%f");
186 fFormatArgs.push_back(cppCode);
187 } else if (type == *fContext.fInt_Type) {
188 this->write("%d");
189 fFormatArgs.push_back(cppCode);
190 } else if (type == *fContext.fBool_Type) {
191 this->write("%s");
192 fFormatArgs.push_back("(" + cppCode + " ? \"true\" : \"false\")");
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400193 } else if (type == *fContext.fFloat2_Type || type == *fContext.fHalf2_Type) {
194 this->write(type.name() + "(%f, %f)");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400195 fFormatArgs.push_back(cppCode + ".fX");
196 fFormatArgs.push_back(cppCode + ".fY");
Ethan Nicholas82399462017-10-16 12:35:44 -0400197 } else if (type == *fContext.fFloat4_Type || type == *fContext.fHalf4_Type) {
198 this->write(type.name() + "(%f, %f, %f, %f)");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400199 switch (layout.fCType) {
200 case Layout::CType::kSkPMColor:
201 fFormatArgs.push_back("SkGetPackedR32(" + cppCode + ") / 255.0");
202 fFormatArgs.push_back("SkGetPackedG32(" + cppCode + ") / 255.0");
203 fFormatArgs.push_back("SkGetPackedB32(" + cppCode + ") / 255.0");
204 fFormatArgs.push_back("SkGetPackedA32(" + cppCode + ") / 255.0");
205 break;
Brian Osmanf28e55d2018-10-03 16:35:54 -0400206 case Layout::CType::kSkPMColor4f:
207 fFormatArgs.push_back(cppCode + ".fR");
208 fFormatArgs.push_back(cppCode + ".fG");
209 fFormatArgs.push_back(cppCode + ".fB");
210 fFormatArgs.push_back(cppCode + ".fA");
211 break;
Brian Salomoneca66b32019-06-01 11:18:15 -0400212 case Layout::CType::kSkVector4:
213 fFormatArgs.push_back(cppCode + ".fData[0]");
214 fFormatArgs.push_back(cppCode + ".fData[1]");
215 fFormatArgs.push_back(cppCode + ".fData[2]");
216 fFormatArgs.push_back(cppCode + ".fData[3]");
217 break;
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400218 case Layout::CType::kSkRect: // fall through
219 case Layout::CType::kDefault:
220 fFormatArgs.push_back(cppCode + ".left()");
221 fFormatArgs.push_back(cppCode + ".top()");
222 fFormatArgs.push_back(cppCode + ".right()");
223 fFormatArgs.push_back(cppCode + ".bottom()");
224 break;
225 default:
226 SkASSERT(false);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400227 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500228 } else if (type.kind() == Type::kEnum_Kind) {
229 this->write("%d");
230 fFormatArgs.push_back("(int) " + cppCode);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400231 } else if (type == *fContext.fInt4_Type ||
232 type == *fContext.fShort4_Type ||
233 type == *fContext.fByte4_Type) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500234 this->write(type.name() + "(%d, %d, %d, %d)");
235 fFormatArgs.push_back(cppCode + ".left()");
236 fFormatArgs.push_back(cppCode + ".top()");
237 fFormatArgs.push_back(cppCode + ".right()");
238 fFormatArgs.push_back(cppCode + ".bottom()");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400239 } else {
Ethan Nicholas82399462017-10-16 12:35:44 -0400240 printf("unsupported runtime value type '%s'\n", String(type.fName).c_str());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400241 SkASSERT(false);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400242 }
243}
244
245void CPPCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
246 if (is_private(var)) {
Ethan Nicholasd608c092017-10-26 09:30:08 -0400247 this->writeRuntimeValue(var.fType, var.fModifiers.fLayout, var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400248 } else {
249 this->writeExpression(value, kTopLevel_Precedence);
250 }
251}
252
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400253String CPPCodeGenerator::getSamplerHandle(const Variable& var) {
254 int samplerCount = 0;
Ethan Nicholas68990be2017-07-13 09:36:52 -0400255 for (const auto param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400256 if (&var == param) {
257 return "args.fTexSamplers[" + to_string(samplerCount) + "]";
258 }
259 if (param->fType.kind() == Type::kSampler_Kind) {
260 ++samplerCount;
261 }
262 }
263 ABORT("should have found sampler in parameters\n");
264}
265
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400266void CPPCodeGenerator::writeIntLiteral(const IntLiteral& i) {
267 this->write(to_string((int32_t) i.fValue));
268}
269
Ethan Nicholas82399462017-10-16 12:35:44 -0400270void CPPCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
271 if (fCPPMode) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400272 SkASSERT(swizzle.fComponents.size() == 1); // no support for multiple swizzle components yet
Ethan Nicholas82399462017-10-16 12:35:44 -0400273 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
274 switch (swizzle.fComponents[0]) {
275 case 0: this->write(".left()"); break;
276 case 1: this->write(".top()"); break;
277 case 2: this->write(".right()"); break;
278 case 3: this->write(".bottom()"); break;
279 }
280 } else {
281 INHERITED::writeSwizzle(swizzle);
282 }
283}
284
Ethan Nicholas762466e2017-06-29 10:03:38 -0400285void CPPCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400286 if (fCPPMode) {
287 this->write(ref.fVariable.fName);
288 return;
289 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400290 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
291 case SK_INCOLOR_BUILTIN:
292 this->write("%s");
Michael Ludwig231de032018-08-30 14:33:01 -0400293 // EmitArgs.fInputColor is automatically set to half4(1) if
294 // no input was specified
295 fFormatArgs.push_back(String("args.fInputColor"));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400296 break;
297 case SK_OUTCOLOR_BUILTIN:
298 this->write("%s");
299 fFormatArgs.push_back(String("args.fOutputColor"));
300 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -0400301 case SK_WIDTH_BUILTIN:
302 this->write("sk_Width");
303 break;
304 case SK_HEIGHT_BUILTIN:
305 this->write("sk_Height");
306 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400307 default:
308 if (ref.fVariable.fType.kind() == Type::kSampler_Kind) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400309 this->write("%s");
310 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerVariable(" +
Stephen Whited523a062019-06-19 13:12:46 -0400311 this->getSamplerHandle(ref.fVariable) + ")");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400312 return;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400313 }
314 if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag) {
315 this->write("%s");
316 String name = ref.fVariable.fName;
Brian Osman1cb41712017-10-19 12:54:52 -0400317 String var = String::printf("args.fUniformHandler->getUniformCStr(%sVar)",
318 HCodeGenerator::FieldName(name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400319 String code;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400320 if (ref.fVariable.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400321 code = String::printf("%sVar.isValid() ? %s : \"%s\"",
322 HCodeGenerator::FieldName(name.c_str()).c_str(),
323 var.c_str(),
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400324 default_value(ref.fVariable.fType).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400325 } else {
326 code = var;
327 }
328 fFormatArgs.push_back(code);
329 } else if (SectionAndParameterHelper::IsParameter(ref.fVariable)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700330 String name(ref.fVariable.fName);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400331 this->writeRuntimeValue(ref.fVariable.fType, ref.fVariable.fModifiers.fLayout,
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400332 String::printf("_outer.%s", name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400333 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700334 this->write(ref.fVariable.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400335 }
336 }
337}
338
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400339void CPPCodeGenerator::writeIfStatement(const IfStatement& s) {
340 if (s.fIsStatic) {
341 this->write("@");
342 }
343 INHERITED::writeIfStatement(s);
344}
345
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400346void CPPCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
347 if (fInMain) {
348 fErrors.error(s.fOffset, "fragmentProcessor main() may not contain return statements");
349 }
350 INHERITED::writeReturnStatement(s);
351}
352
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400353void CPPCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
354 if (s.fIsStatic) {
355 this->write("@");
356 }
357 INHERITED::writeSwitchStatement(s);
358}
359
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400360void CPPCodeGenerator::writeFieldAccess(const FieldAccess& access) {
361 if (access.fBase->fType.name() == "fragmentProcessor") {
362 // Special field access on fragment processors are converted into function calls on
363 // GrFragmentProcessor's getters.
364 if (access.fBase->fKind != Expression::kVariableReference_Kind) {
365 fErrors.error(access.fBase->fOffset, "fragmentProcessor must be a reference\n");
366 return;
367 }
368
369 const Type::Field& field = fContext.fFragmentProcessor_Type->fields()[access.fFieldIndex];
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500370 const Variable& var = ((const VariableReference&) *access.fBase).fVariable;
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400371 String cppAccess = String::printf("_outer.childProcessor(_outer.%s_index).%s()",
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500372 String(var.fName).c_str(),
373 String(field.fName).c_str());
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400374
375 if (fCPPMode) {
376 this->write(cppAccess.c_str());
377 } else {
378 writeRuntimeValue(*field.fType, Layout(), cppAccess);
379 }
380 return;
381 }
382 INHERITED::writeFieldAccess(access);
383}
384
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500385int CPPCodeGenerator::getChildFPIndex(const Variable& var) const {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400386 int index = 0;
387 bool found = false;
388 for (const auto& p : fProgram) {
389 if (ProgramElement::kVar_Kind == p.fKind) {
390 const VarDeclarations& decls = (const VarDeclarations&) p;
391 for (const auto& raw : decls.fVars) {
392 const VarDeclaration& decl = (VarDeclaration&) *raw;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500393 if (decl.fVar == &var) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400394 found = true;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500395 } else if (decl.fVar->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400396 ++index;
397 }
398 }
399 }
400 if (found) {
401 break;
402 }
403 }
404 SkASSERT(found);
405 return index;
406}
407
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400408void CPPCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas13863662019-07-29 13:05:15 -0400409 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample" &&
410 c.fArguments[0]->fType.kind() != Type::Kind::kSampler_Kind) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400411 // Sanity checks that are detected by function definition in sksl_fp.inc
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400412 SkASSERT(c.fArguments.size() >= 1 && c.fArguments.size() <= 3);
Florin Malita390f9bd2019-03-04 12:25:57 -0500413 SkASSERT("fragmentProcessor" == c.fArguments[0]->fType.name() ||
414 "fragmentProcessor?" == c.fArguments[0]->fType.name());
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400415
416 // Actually fail during compilation if arguments with valid types are
Ethan Nicholas13863662019-07-29 13:05:15 -0400417 // provided that are not variable references, since sample() is a
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400418 // special function that impacts code emission.
419 if (c.fArguments[0]->fKind != Expression::kVariableReference_Kind) {
420 fErrors.error(c.fArguments[0]->fOffset,
Ethan Nicholas13863662019-07-29 13:05:15 -0400421 "sample()'s fragmentProcessor argument must be a variable reference\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400422 return;
423 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500424 const Variable& child = ((const VariableReference&) *c.fArguments[0]).fVariable;
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400425
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400426 // Start a new extra emit code section so that the emitted child processor can depend on
427 // sksl variables defined in earlier sksl code.
428 this->newExtraEmitCodeBlock();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400429
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400430 // Set to the empty string when no input color parameter should be emitted, which means this
431 // must be properly formatted with a prefixed comma when the parameter should be inserted
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400432 // into the invokeChild() parameter list.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400433 String inputArg;
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400434 if (c.fArguments.size() > 1 && c.fArguments[1]->fType.name() == "half4") {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400435 // Use the invokeChild() variant that accepts an input color, so convert the 2nd
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400436 // argument's expression into C++ code that produces sksl stored in an SkString.
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400437 String inputName = "_input" + to_string(c.fOffset);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400438 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments[1], inputName));
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400439
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400440 // invokeChild() needs a char*
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400441 inputArg = ", " + inputName + ".c_str()";
442 }
443
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400444 bool hasCoords = c.fArguments.back()->fType.name() == "float2";
445
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400446 // Write the output handling after the possible input handling
Ethan Nicholas13863662019-07-29 13:05:15 -0400447 String childName = "_sample" + to_string(c.fOffset);
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000448 addExtraEmitCodeLine("SkString " + childName + "(\"" + childName + "\");");
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400449 String coordsName;
450 if (hasCoords) {
451 coordsName = "_coords" + to_string(c.fOffset);
452 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), coordsName));
453 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500454 if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400455 addExtraEmitCodeLine("if (_outer." + String(child.fName) + "_index >= 0) {\n ");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500456 }
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400457 if (hasCoords) {
458 addExtraEmitCodeLine("this->invokeChild(_outer." + String(child.fName) + "_index" +
459 inputArg + ", &" + childName + ", args, " + coordsName +
460 ".c_str());");
461 } else {
462 addExtraEmitCodeLine("this->invokeChild(_outer." + String(child.fName) + "_index" +
463 inputArg + ", &" + childName + ", args);");
464 }
465
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500466 if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000467 // Null FPs are not emitted, but their output can still be referenced in dependent
468 // expressions - thus we always declare the variable.
469 // Note: this is essentially dead code required to satisfy the compiler, because
470 // 'process' function calls should always be guarded at a higher level, in the .fp
471 // source.
472 addExtraEmitCodeLine(
473 "} else {"
474 " fragBuilder->codeAppendf(\"half4 %s;\", " + childName + ".c_str());"
475 "}");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500476 }
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000477 this->write("%s");
478 fFormatArgs.push_back(childName + ".c_str()");
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400479 return;
480 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400481 if (c.fFunction.fBuiltin) {
482 INHERITED::writeFunctionCall(c);
483 } else {
484 this->write("%s");
485 fFormatArgs.push_back((String(c.fFunction.fName) + "_name.c_str()").c_str());
486 this->write("(");
487 const char* separator = "";
488 for (const auto& arg : c.fArguments) {
489 this->write(separator);
490 separator = ", ";
491 this->writeExpression(*arg, kSequence_Precedence);
492 }
493 this->write(")");
494 }
Ethan Nicholas13863662019-07-29 13:05:15 -0400495 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample") {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400496 this->write(".%s");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400497 SkASSERT(c.fArguments.size() >= 1);
498 SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400499 String sampler = this->getSamplerHandle(((VariableReference&) *c.fArguments[0]).fVariable);
500 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
501 ").c_str()");
502 }
503}
504
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400505static const char* glsltype_string(const Context& context, const Type& type) {
506 if (type == *context.fFloat_Type) {
507 return "kFloat_GrSLType";
508 } else if (type == *context.fHalf_Type) {
509 return "kHalf_GrSLType";
510 } else if (type == *context.fFloat2_Type) {
511 return "kFloat2_GrSLType";
512 } else if (type == *context.fHalf2_Type) {
513 return "kHalf2_GrSLType";
514 } else if (type == *context.fFloat4_Type) {
515 return "kFloat4_GrSLType";
516 } else if (type == *context.fHalf4_Type) {
517 return "kHalf4_GrSLType";
518 } else if (type == *context.fFloat4x4_Type) {
519 return "kFloat4x4_GrSLType";
520 } else if (type == *context.fHalf4x4_Type) {
521 return "kHalf4x4_GrSLType";
522 } else if (type == *context.fVoid_Type) {
523 return "kVoid_GrSLType";
524 }
525 SkASSERT(false);
526 return nullptr;
527}
528
Ethan Nicholas762466e2017-06-29 10:03:38 -0400529void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400530 const FunctionDeclaration& decl = f.fDeclaration;
531 fFunctionHeader = "";
532 OutputStream* oldOut = fOut;
533 StringStream buffer;
534 fOut = &buffer;
535 if (decl.fName == "main") {
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400536 fInMain = true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400537 for (const auto& s : ((Block&) *f.fBody).fStatements) {
538 this->writeStatement(*s);
539 this->writeLine();
540 }
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400541 fInMain = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400542
543 fOut = oldOut;
544 this->write(fFunctionHeader);
545 this->write(buffer.str());
546 } else {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400547 this->addExtraEmitCodeLine("SkString " + decl.fName + "_name;");
548 String args = "const GrShaderVar " + decl.fName + "_args[] = { ";
549 const char* separator = "";
550 for (const auto& param : decl.fParameters) {
551 args += String(separator) + "GrShaderVar(\"" + param->fName + "\", " +
552 glsltype_string(fContext, param->fType) + ")";
553 separator = ", ";
554 }
555 args += "};";
556 this->addExtraEmitCodeLine(args.c_str());
557 for (const auto& s : ((Block&) *f.fBody).fStatements) {
558 this->writeStatement(*s);
559 this->writeLine();
560 }
561
562 fOut = oldOut;
563 String emit = "fragBuilder->emitFunction(";
564 emit += glsltype_string(fContext, decl.fReturnType);
565 emit += ", \"" + decl.fName + "\"";
566 emit += ", " + to_string((int64_t) decl.fParameters.size());
567 emit += ", " + decl.fName + "_args";
568 emit += ", \"" + buffer.str() + "\"";
569 emit += ", &" + decl.fName + "_name);";
570 this->addExtraEmitCodeLine(emit.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400571 }
572}
573
574void CPPCodeGenerator::writeSetting(const Setting& s) {
575 static constexpr const char* kPrefix = "sk_Args.";
576 if (!strncmp(s.fName.c_str(), kPrefix, strlen(kPrefix))) {
577 const char* name = s.fName.c_str() + strlen(kPrefix);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400578 this->writeRuntimeValue(s.fType, Layout(), HCodeGenerator::FieldName(name).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400579 } else {
580 this->write(s.fName.c_str());
581 }
582}
583
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400584bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400585 const Section* s = fSectionAndParameterHelper.getSection(name);
586 if (s) {
587 this->writef("%s%s", prefix, s->fText.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400588 return true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400589 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400590 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400591}
592
593void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
594 if (p.fKind == ProgramElement::kSection_Kind) {
595 return;
596 }
597 if (p.fKind == ProgramElement::kVar_Kind) {
598 const VarDeclarations& decls = (const VarDeclarations&) p;
599 if (!decls.fVars.size()) {
600 return;
601 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000602 const Variable& var = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400603 if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
604 -1 != var.fModifiers.fLayout.fBuiltin) {
605 return;
606 }
607 }
608 INHERITED::writeProgramElement(p);
609}
610
611void CPPCodeGenerator::addUniform(const Variable& var) {
612 if (!needs_uniform_var(var)) {
613 return;
614 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400615 if (var.fModifiers.fLayout.fWhen.fLength) {
616 this->writef(" if (%s) {\n ", String(var.fModifiers.fLayout.fWhen).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400617 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400618 const char* type = glsltype_string(fContext, var.fType);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700619 String name(var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400620 this->writef(" %sVar = args.fUniformHandler->addUniform(kFragment_GrShaderFlag, %s, "
Ethan Nicholas858fecc2019-03-07 13:19:18 -0500621 "\"%s\");\n", HCodeGenerator::FieldName(name.c_str()).c_str(), type,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700622 name.c_str());
Ethan Nicholasfc994162019-06-06 10:04:27 -0400623 if (var.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400624 this->write(" }\n");
625 }
626}
627
Ethan Nicholascd700e92018-08-24 16:43:57 -0400628void CPPCodeGenerator::writeInputVars() {
629}
630
Ethan Nicholas762466e2017-06-29 10:03:38 -0400631void CPPCodeGenerator::writePrivateVars() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400632 for (const auto& p : fProgram) {
633 if (ProgramElement::kVar_Kind == p.fKind) {
634 const VarDeclarations& decls = (const VarDeclarations&) p;
635 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000636 VarDeclaration& decl = (VarDeclaration&) *raw;
637 if (is_private(*decl.fVar)) {
638 if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
639 fErrors.error(decl.fOffset,
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400640 "fragmentProcessor variables must be declared 'in'");
641 return;
642 }
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500643 this->writef("%s %s = %s;\n",
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000644 HCodeGenerator::FieldType(fContext, decl.fVar->fType,
645 decl.fVar->fModifiers.fLayout).c_str(),
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500646 String(decl.fVar->fName).c_str(),
647 default_value(*decl.fVar).c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400648 } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
649 // An auto-tracked uniform in variable, so add a field to hold onto the prior
650 // state. Note that tracked variables must be uniform in's and that is validated
651 // before writePrivateVars() is called.
652 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
653 SkASSERT(mapper && mapper->supportsTracking());
654
655 String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
656 // The member statement is different if the mapper reports a default value
657 if (mapper->defaultValue().size() > 0) {
658 this->writef("%s %sPrev = %s;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400659 Layout::CTypeToStr(mapper->ctype()), name.c_str(),
Michael Ludwiga4275592018-08-31 10:52:47 -0400660 mapper->defaultValue().c_str());
661 } else {
662 this->writef("%s %sPrev;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400663 Layout::CTypeToStr(mapper->ctype()), name.c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400664 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400665 }
666 }
667 }
668 }
669}
670
671void CPPCodeGenerator::writePrivateVarValues() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400672 for (const auto& p : fProgram) {
673 if (ProgramElement::kVar_Kind == p.fKind) {
674 const VarDeclarations& decls = (const VarDeclarations&) p;
675 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000676 VarDeclaration& decl = (VarDeclaration&) *raw;
677 if (is_private(*decl.fVar) && decl.fValue) {
678 this->writef("%s = ", String(decl.fVar->fName).c_str());
Ethan Nicholas82399462017-10-16 12:35:44 -0400679 fCPPMode = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000680 this->writeExpression(*decl.fValue, kAssignment_Precedence);
Ethan Nicholas82399462017-10-16 12:35:44 -0400681 fCPPMode = false;
682 this->write(";\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400683 }
684 }
685 }
686 }
687}
688
Ethan Nicholas82399462017-10-16 12:35:44 -0400689static bool is_accessible(const Variable& var) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500690 const Type& type = var.fType.nonnullable();
691 return Type::kSampler_Kind != type.kind() &&
692 Type::kOther_Kind != type.kind();
Ethan Nicholas82399462017-10-16 12:35:44 -0400693}
694
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400695void CPPCodeGenerator::newExtraEmitCodeBlock() {
696 // This should only be called when emitting SKSL for emitCode(), which can be detected if the
697 // cpp buffer is not null, and the cpp buffer is not the current output.
698 SkASSERT(fCPPBuffer && fCPPBuffer != fOut);
699
700 // Start a new block as an empty string
701 fExtraEmitCodeBlocks.push_back("");
702 // Mark its location in the output buffer, uses ${\d} for the token since ${} will not occur in
703 // valid sksl and makes detection trivial.
704 this->writef("${%zu}", fExtraEmitCodeBlocks.size() - 1);
705}
706
707void CPPCodeGenerator::addExtraEmitCodeLine(const String& toAppend) {
708 SkASSERT(fExtraEmitCodeBlocks.size() > 0);
709 String& currentBlock = fExtraEmitCodeBlocks[fExtraEmitCodeBlocks.size() - 1];
710 // Automatically add indentation and newline
711 currentBlock += " " + toAppend + "\n";
712}
713
714void CPPCodeGenerator::flushEmittedCode() {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400715 if (fCPPBuffer == nullptr) {
716 // Not actually within writeEmitCode() so nothing to flush
717 return;
718 }
719
720 StringStream* skslBuffer = static_cast<StringStream*>(fOut);
721
722 String sksl = skslBuffer->str();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400723 // Empty the accumulation buffer since its current contents are consumed.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400724 skslBuffer->reset();
725
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400726 // Switch to the cpp buffer
Michael Ludwigd0440192018-09-07 14:24:52 +0000727 fOut = fCPPBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400728
729 // Iterate through the sksl, keeping track of where the last statement ended (e.g. the latest
730 // encountered ';', '{', or '}'). If an extra emit code block token is encountered then the
731 // code from 0 to last statement end is sent to writeCodeAppend, the extra code block is
732 // appended to the cpp buffer, and then the sksl string is trimmed to start where the last
733 // statement left off (minus the encountered token).
734 size_t i = 0;
735 int flushPoint = -1;
736 int tokenStart = -1;
737 while (i < sksl.size()) {
738 if (tokenStart >= 0) {
739 // Looking for the end of the token
740 if (sksl[i] == '}') {
741 // Must append the sksl from 0 to flushPoint (inclusive) then the extra code
742 // accumulated in the block with index parsed from chars [tokenStart+2, i-1]
743 String toFlush = String(sksl.c_str(), flushPoint + 1);
744 // writeCodeAppend automatically removes the format args that it consumed, so
745 // fFormatArgs will be in a valid state for any future sksl
746 this->writeCodeAppend(toFlush);
747
748 int codeBlock = stoi(String(sksl.c_str() + tokenStart + 2, i - tokenStart - 2));
749 SkASSERT(codeBlock < (int) fExtraEmitCodeBlocks.size());
750 if (fExtraEmitCodeBlocks[codeBlock].size() > 0) {
751 this->write(fExtraEmitCodeBlocks[codeBlock].c_str());
752 }
753
754 // Now reset the sksl buffer to start after the flush point, but remove the token.
755 String compacted = String(sksl.c_str() + flushPoint + 1,
756 tokenStart - flushPoint - 1);
757 if (i < sksl.size() - 1) {
758 compacted += String(sksl.c_str() + i + 1, sksl.size() - i - 1);
759 }
760 sksl = compacted;
761
762 // And reset iteration
763 i = -1;
764 flushPoint = -1;
765 tokenStart = -1;
766 }
767 } else {
768 // Looking for the start of extra emit block tokens, and tracking when statements end
769 if (sksl[i] == ';' || sksl[i] == '{' || sksl[i] == '}') {
770 flushPoint = i;
771 } else if (i < sksl.size() - 1 && sksl[i] == '$' && sksl[i + 1] == '{') {
772 // found an extra emit code block token
773 tokenStart = i++;
774 }
775 }
776 i++;
Michael Ludwigd0440192018-09-07 14:24:52 +0000777 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400778
779 // Once we've gone through the sksl string to this point, there are no remaining extra emit
780 // code blocks to interleave, so append the remainder as usual.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400781 this->writeCodeAppend(sksl);
782
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400783 // After appending, switch back to the emptied sksl buffer and reset the extra code blocks
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400784 fOut = skslBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400785 fExtraEmitCodeBlocks.clear();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400786}
787
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400788void CPPCodeGenerator::writeCodeAppend(const String& code) {
789 // codeAppendf can only handle appending 1024 bytes at a time, so we need to break the string
790 // into chunks. Unfortunately we can't tell exactly how long the string is going to end up,
791 // because printf escape sequences get replaced by strings of unknown length, but keeping the
792 // format string below 512 bytes is probably safe.
793 static constexpr size_t maxChunkSize = 512;
794 size_t start = 0;
795 size_t index = 0;
796 size_t argStart = 0;
797 size_t argCount;
798 while (index < code.size()) {
799 argCount = 0;
800 this->write(" fragBuilder->codeAppendf(\"");
801 while (index < code.size() && index < start + maxChunkSize) {
802 if ('%' == code[index]) {
803 if (index == start + maxChunkSize - 1 || index == code.size() - 1) {
804 break;
805 }
806 if (code[index + 1] != '%') {
807 ++argCount;
808 }
Ethan Nicholasef0c9fd2017-10-30 10:04:14 -0400809 } else if ('\\' == code[index] && index == start + maxChunkSize - 1) {
810 // avoid splitting an escape sequence that happens to fall across a chunk boundary
811 break;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400812 }
813 ++index;
814 }
815 fOut->write(code.c_str() + start, index - start);
816 this->write("\"");
817 for (size_t i = argStart; i < argStart + argCount; ++i) {
818 this->writef(", %s", fFormatArgs[i].c_str());
819 }
820 this->write(");\n");
821 argStart += argCount;
822 start = index;
823 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400824
825 // argStart is equal to the number of fFormatArgs that were consumed
826 // so they should be removed from the list
827 if (argStart > 0) {
828 fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argStart);
829 }
830}
831
832String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
833 const String& cppVar) {
834 // To do this conversion, we temporarily switch the sksl output stream
835 // to an empty stringstream and reset the format args to empty.
836 OutputStream* oldSKSL = fOut;
837 StringStream exprBuffer;
838 fOut = &exprBuffer;
839
840 std::vector<String> oldArgs(fFormatArgs);
841 fFormatArgs.clear();
842
843 // Convert the argument expression into a format string and args
844 this->writeExpression(e, Precedence::kTopLevel_Precedence);
845 std::vector<String> newArgs(fFormatArgs);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400846 String expr = exprBuffer.str();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400847
848 // After generating, restore the original output stream and format args
849 fFormatArgs = oldArgs;
850 fOut = oldSKSL;
851
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400852 // The sksl written to exprBuffer is not processed by flushEmittedCode(), so any extra emit code
853 // block tokens won't get handled. So we need to strip them from the expression and stick them
854 // to the end of the original sksl stream.
855 String exprFormat = "";
856 int tokenStart = -1;
857 for (size_t i = 0; i < expr.size(); i++) {
858 if (tokenStart >= 0) {
859 if (expr[i] == '}') {
860 // End of the token, so append the token to fOut
861 fOut->write(expr.c_str() + tokenStart, i - tokenStart + 1);
862 tokenStart = -1;
863 }
864 } else {
865 if (i < expr.size() - 1 && expr[i] == '$' && expr[i + 1] == '{') {
866 tokenStart = i++;
867 } else {
868 exprFormat += expr[i];
869 }
870 }
871 }
872
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400873 // Now build the final C++ code snippet from the format string and args
874 String cppExpr;
875 if (newArgs.size() == 0) {
876 // This was a static expression, so we can simplify the input
877 // color declaration in the emitted code to just a static string
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400878 cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400879 } else {
880 // String formatting must occur dynamically, so have the C++ declaration
881 // use SkStringPrintf with the format args that were accumulated
882 // when the expression was written.
883 cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
884 for (size_t i = 0; i < newArgs.size(); i++) {
885 cppExpr += ", " + newArgs[i];
886 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400887 cppExpr += ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400888 }
889 return cppExpr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400890}
891
Ethan Nicholas762466e2017-06-29 10:03:38 -0400892bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
893 this->write(" void emitCode(EmitArgs& args) override {\n"
894 " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
895 this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
896 " (void) _outer;\n",
897 fFullName.c_str(), fFullName.c_str());
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400898 for (const auto& p : fProgram) {
899 if (ProgramElement::kVar_Kind == p.fKind) {
900 const VarDeclarations& decls = (const VarDeclarations&) p;
901 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000902 VarDeclaration& decl = (VarDeclaration&) *raw;
903 String nameString(decl.fVar->fName);
Ethan Nicholas82399462017-10-16 12:35:44 -0400904 const char* name = nameString.c_str();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000905 if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
906 is_accessible(*decl.fVar)) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400907 this->writef(" auto %s = _outer.%s;\n"
Ethan Nicholas82399462017-10-16 12:35:44 -0400908 " (void) %s;\n",
909 name, name, name);
910 }
911 }
912 }
913 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400914 this->writePrivateVarValues();
915 for (const auto u : uniforms) {
916 this->addUniform(*u);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400917 }
918 this->writeSection(EMIT_CODE_SECTION);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400919
920 // Save original buffer as the CPP buffer for flushEmittedCode()
921 fCPPBuffer = fOut;
922 StringStream skslBuffer;
923 fOut = &skslBuffer;
924
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400925 this->newExtraEmitCodeBlock();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400926 bool result = INHERITED::generateCode();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400927 this->flushEmittedCode();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400928
929 // Then restore the original CPP buffer and close the function
930 fOut = fCPPBuffer;
931 fCPPBuffer = nullptr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400932 this->write(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400933 return result;
934}
935
936void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
937 const char* fullName = fFullName.c_str();
Ethan Nicholas68990be2017-07-13 09:36:52 -0400938 const Section* section = fSectionAndParameterHelper.getSection(SET_DATA_SECTION);
939 const char* pdman = section ? section->fArgument.c_str() : "pdman";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400940 this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
941 "const GrFragmentProcessor& _proc) override {\n",
942 pdman);
943 bool wroteProcessor = false;
944 for (const auto u : uniforms) {
Michael Ludwiga4275592018-08-31 10:52:47 -0400945 if (is_uniform_in(*u)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400946 if (!wroteProcessor) {
947 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
948 wroteProcessor = true;
949 this->writef(" {\n");
950 }
Michael Ludwiga4275592018-08-31 10:52:47 -0400951
952 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
953 SkASSERT(mapper);
954
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700955 String nameString(u->fName);
956 const char* name = nameString.c_str();
Michael Ludwiga4275592018-08-31 10:52:47 -0400957
958 // Switches for setData behavior in the generated code
959 bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
960 bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
961 bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
962
963 String uniformName = HCodeGenerator::FieldName(name) + "Var";
964
965 String indent = " "; // 8 by default, 12 when nested for conditional uniforms
966 if (conditionalUniform) {
967 // Add a pre-check to make sure the uniform was emitted
968 // before trying to send any data to the GPU
969 this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
970 indent += " ";
971 }
972
973 String valueVar = "";
974 if (needsValueDeclaration) {
975 valueVar.appendf("%sValue", name);
976 // Use AccessType since that will match the return type of _outer's public API.
977 String valueType = HCodeGenerator::AccessType(fContext, u->fType,
978 u->fModifiers.fLayout);
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400979 this->writef("%s%s %s = _outer.%s;\n",
Michael Ludwiga4275592018-08-31 10:52:47 -0400980 indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400981 } else {
Michael Ludwiga4275592018-08-31 10:52:47 -0400982 // Not tracked and the mapper only needs to use the value once
983 // so send it a safe expression instead of the variable name
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400984 valueVar.appendf("(_outer.%s)", name);
Michael Ludwiga4275592018-08-31 10:52:47 -0400985 }
986
987 if (isTracked) {
988 SkASSERT(mapper->supportsTracking());
989
990 String prevVar = HCodeGenerator::FieldName(name) + "Prev";
991 this->writef("%sif (%s) {\n"
992 "%s %s;\n"
993 "%s %s;\n"
994 "%s}\n", indent.c_str(),
995 mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
996 mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
997 mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
998 } else {
999 this->writef("%s%s;\n", indent.c_str(),
1000 mapper->setUniform(pdman, uniformName, valueVar).c_str());
1001 }
1002
1003 if (conditionalUniform) {
1004 // Close the earlier precheck block
1005 this->writef(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001006 }
1007 }
1008 }
1009 if (wroteProcessor) {
1010 this->writef(" }\n");
1011 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001012 if (section) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001013 int samplerIndex = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001014 for (const auto& p : fProgram) {
1015 if (ProgramElement::kVar_Kind == p.fKind) {
1016 const VarDeclarations& decls = (const VarDeclarations&) p;
1017 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001018 VarDeclaration& decl = (VarDeclaration&) *raw;
1019 String nameString(decl.fVar->fName);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001020 const char* name = nameString.c_str();
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001021 if (decl.fVar->fType.kind() == Type::kSampler_Kind) {
1022 this->writef(" GrSurfaceProxy& %sProxy = "
1023 "*_outer.textureSampler(%d).proxy();\n",
1024 name, samplerIndex);
Brian Salomonfd98c2c2018-07-31 17:25:29 -04001025 this->writef(" GrTexture& %s = *%sProxy.peekTexture();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001026 name, name);
1027 this->writef(" (void) %s;\n", name);
1028 ++samplerIndex;
1029 } else if (needs_uniform_var(*decl.fVar)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001030 this->writef(" UniformHandle& %s = %sVar;\n"
1031 " (void) %s;\n",
1032 name, HCodeGenerator::FieldName(name).c_str(), name);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001033 } else if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
1034 decl.fVar->fType != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001035 if (!wroteProcessor) {
1036 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
1037 fullName);
1038 wroteProcessor = true;
1039 }
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001040 this->writef(" auto %s = _outer.%s;\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001041 " (void) %s;\n",
1042 name, name, name);
1043 }
1044 }
1045 }
1046 }
1047 this->writeSection(SET_DATA_SECTION);
1048 }
1049 this->write(" }\n");
1050}
1051
Brian Salomonf7dcd762018-07-30 14:48:15 -04001052void CPPCodeGenerator::writeOnTextureSampler() {
1053 bool foundSampler = false;
1054 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1055 if (param->fType.kind() == Type::kSampler_Kind) {
1056 if (!foundSampler) {
1057 this->writef(
1058 "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
1059 "index) const {\n",
1060 fFullName.c_str());
1061 this->writef(" return IthTextureSampler(index, %s",
1062 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1063 foundSampler = true;
1064 } else {
1065 this->writef(", %s",
1066 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1067 }
1068 }
1069 }
1070 if (foundSampler) {
1071 this->write(");\n}\n");
1072 }
1073}
1074
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001075void CPPCodeGenerator::writeClone() {
1076 if (!this->writeSection(CLONE_SECTION)) {
1077 if (fSectionAndParameterHelper.getSection(FIELDS_SECTION)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001078 fErrors.error(0, "fragment processors with custom @fields must also have a custom"
1079 "@clone");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001080 }
1081 this->writef("%s::%s(const %s& src)\n"
Ethan Nicholasabff9562017-10-09 10:54:08 -04001082 ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
1083 fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001084 const auto transforms = fSectionAndParameterHelper.getSections(COORD_TRANSFORM_SECTION);
1085 for (size_t i = 0; i < transforms.size(); ++i) {
1086 const Section& s = *transforms[i];
1087 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
1088 this->writef("\n, %s(src.%s)", fieldName.c_str(), fieldName.c_str());
1089 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001090 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Robert Phillipsbce7d862019-02-21 22:53:57 +00001091 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001092 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
1093 this->writef("\n, %s_index(src.%s_index)",
1094 fieldName.c_str(),
1095 fieldName.c_str());
1096 } else {
1097 this->writef("\n, %s(src.%s)",
1098 fieldName.c_str(),
1099 fieldName.c_str());
1100 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001101 }
Ethan Nicholasabff9562017-10-09 10:54:08 -04001102 this->writef(" {\n");
Brian Salomonf7dcd762018-07-30 14:48:15 -04001103 int samplerCount = 0;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001104 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1105 if (param->fType.kind() == Type::kSampler_Kind) {
Brian Salomonf7dcd762018-07-30 14:48:15 -04001106 ++samplerCount;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001107 } else if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
1108 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
1109 if (param->fType.kind() == Type::kNullable_Kind) {
1110 this->writef(" if (%s_index >= 0) {\n ", fieldName.c_str());
1111 }
1112 this->writef(" this->registerChildProcessor(src.childProcessor(%s_index)."
1113 "clone());\n", fieldName.c_str());
1114 if (param->fType.kind() == Type::kNullable_Kind) {
1115 this->writef(" }\n");
1116 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001117 }
1118 }
Brian Salomonf7dcd762018-07-30 14:48:15 -04001119 if (samplerCount) {
1120 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
1121 }
Ethan Nicholas929a6812018-08-06 14:56:59 -04001122 for (size_t i = 0; i < transforms.size(); ++i) {
1123 const Section& s = *transforms[i];
1124 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
1125 this->writef(" this->addCoordTransform(&%s);\n", fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001126 }
1127 this->write("}\n");
Brian Salomonaff329b2017-08-11 09:40:37 -04001128 this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
1129 fFullName.c_str());
1130 this->writef(" return std::unique_ptr<GrFragmentProcessor>(new %s(*this));\n",
1131 fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001132 this->write("}\n");
1133 }
1134}
1135
Ethan Nicholas762466e2017-06-29 10:03:38 -04001136void CPPCodeGenerator::writeTest() {
Ethan Nicholas68990be2017-07-13 09:36:52 -04001137 const Section* test = fSectionAndParameterHelper.getSection(TEST_CODE_SECTION);
1138 if (test) {
Brian Salomonaff329b2017-08-11 09:40:37 -04001139 this->writef(
1140 "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
1141 "#if GR_TEST_UTILS\n"
1142 "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
1143 fFullName.c_str(),
1144 fFullName.c_str(),
1145 test->fArgument.c_str());
Ethan Nicholas68990be2017-07-13 09:36:52 -04001146 this->writeSection(TEST_CODE_SECTION);
1147 this->write("}\n"
1148 "#endif\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001149 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001150}
1151
1152void CPPCodeGenerator::writeGetKey() {
1153 this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
1154 "GrProcessorKeyBuilder* b) const {\n",
1155 fFullName.c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001156 for (const auto& p : fProgram) {
1157 if (ProgramElement::kVar_Kind == p.fKind) {
1158 const VarDeclarations& decls = (const VarDeclarations&) p;
1159 for (const auto& raw : decls.fVars) {
1160 const VarDeclaration& decl = (VarDeclaration&) *raw;
1161 const Variable& var = *decl.fVar;
1162 String nameString(var.fName);
1163 const char* name = nameString.c_str();
1164 if (var.fModifiers.fLayout.fKey != Layout::kNo_Key &&
1165 (var.fModifiers.fFlags & Modifiers::kUniform_Flag)) {
1166 fErrors.error(var.fOffset,
1167 "layout(key) may not be specified on uniforms");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001168 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001169 switch (var.fModifiers.fLayout.fKey) {
1170 case Layout::kKey_Key:
1171 if (is_private(var)) {
1172 this->writef("%s %s =",
1173 HCodeGenerator::FieldType(fContext, var.fType,
1174 var.fModifiers.fLayout).c_str(),
1175 String(var.fName).c_str());
1176 if (decl.fValue) {
1177 fCPPMode = true;
1178 this->writeExpression(*decl.fValue, kAssignment_Precedence);
1179 fCPPMode = false;
1180 } else {
1181 this->writef("%s", default_value(var).c_str());
1182 }
1183 this->write(";\n");
1184 }
1185 if (var.fModifiers.fLayout.fWhen.fLength) {
1186 this->writef("if (%s) {", String(var.fModifiers.fLayout.fWhen).c_str());
1187 }
1188 if (var.fType == *fContext.fFloat4x4_Type) {
1189 ABORT("no automatic key handling for float4x4\n");
1190 } else if (var.fType == *fContext.fFloat2_Type) {
1191 this->writef(" b->add32(%s.fX);\n",
1192 HCodeGenerator::FieldName(name).c_str());
1193 this->writef(" b->add32(%s.fY);\n",
1194 HCodeGenerator::FieldName(name).c_str());
1195 } else if (var.fType == *fContext.fFloat4_Type) {
1196 this->writef(" b->add32(%s.x());\n",
1197 HCodeGenerator::FieldName(name).c_str());
1198 this->writef(" b->add32(%s.y());\n",
1199 HCodeGenerator::FieldName(name).c_str());
1200 this->writef(" b->add32(%s.width());\n",
1201 HCodeGenerator::FieldName(name).c_str());
1202 this->writef(" b->add32(%s.height());\n",
1203 HCodeGenerator::FieldName(name).c_str());
1204 } else if (var.fType == *fContext.fHalf4_Type) {
1205 this->writef(" uint16_t red = SkFloatToHalf(%s.fR);\n",
1206 HCodeGenerator::FieldName(name).c_str());
1207 this->writef(" uint16_t green = SkFloatToHalf(%s.fG);\n",
1208 HCodeGenerator::FieldName(name).c_str());
1209 this->writef(" uint16_t blue = SkFloatToHalf(%s.fB);\n",
1210 HCodeGenerator::FieldName(name).c_str());
1211 this->writef(" uint16_t alpha = SkFloatToHalf(%s.fA);\n",
1212 HCodeGenerator::FieldName(name).c_str());
1213 this->write(" b->add32(((uint32_t)red << 16) | green);\n");
1214 this->write(" b->add32(((uint32_t)blue << 16) | alpha);\n");
1215 } else {
1216 this->writef(" b->add32((int32_t) %s);\n",
1217 HCodeGenerator::FieldName(name).c_str());
1218 }
1219 if (var.fModifiers.fLayout.fWhen.fLength) {
1220 this->write("}");
1221 }
1222 break;
1223 case Layout::kIdentity_Key:
1224 if (var.fType.kind() != Type::kMatrix_Kind) {
1225 fErrors.error(var.fOffset,
1226 "layout(key=identity) requires matrix type");
1227 }
1228 this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
1229 HCodeGenerator::FieldName(name).c_str());
1230 break;
1231 case Layout::kNo_Key:
1232 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001233 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001234 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001235 }
1236 }
1237 this->write("}\n");
1238}
1239
1240bool CPPCodeGenerator::generateCode() {
1241 std::vector<const Variable*> uniforms;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001242 for (const auto& p : fProgram) {
1243 if (ProgramElement::kVar_Kind == p.fKind) {
1244 const VarDeclarations& decls = (const VarDeclarations&) p;
1245 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001246 VarDeclaration& decl = (VarDeclaration&) *raw;
1247 if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1248 decl.fVar->fType.kind() != Type::kSampler_Kind) {
1249 uniforms.push_back(decl.fVar);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001250 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001251
1252 if (is_uniform_in(*decl.fVar)) {
1253 // Validate the "uniform in" declarations to make sure they are fully supported,
1254 // instead of generating surprising C++
1255 const UniformCTypeMapper* mapper =
1256 UniformCTypeMapper::Get(fContext, *decl.fVar);
1257 if (mapper == nullptr) {
1258 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1259 + "'s type is not supported for use as a 'uniform in'");
1260 return false;
1261 }
1262 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1263 if (!mapper->supportsTracking()) {
1264 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1265 + "'s type does not support state tracking");
1266 return false;
1267 }
1268 }
1269
1270 } else {
1271 // If it's not a uniform_in, it's an error to be tracked
1272 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1273 fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
1274 return false;
1275 }
1276 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001277 }
1278 }
1279 }
1280 const char* baseName = fName.c_str();
1281 const char* fullName = fFullName.c_str();
Ethan Nicholas130fb3f2018-02-01 12:14:34 -05001282 this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001283 this->writef(kFragmentProcessorHeader, fullName);
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001284 this->writef("#include \"%s.h\"\n\n", fullName);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001285 this->writeSection(CPP_SECTION);
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001286 this->writef("#include \"include/gpu/GrTexture.h\"\n"
1287 "#include \"src/gpu/glsl/GrGLSLFragmentProcessor.h\"\n"
1288 "#include \"src/gpu/glsl/GrGLSLFragmentShaderBuilder.h\"\n"
1289 "#include \"src/gpu/glsl/GrGLSLProgramBuilder.h\"\n"
1290 "#include \"src/sksl/SkSLCPP.h\"\n"
1291 "#include \"src/sksl/SkSLUtil.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001292 "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
1293 "public:\n"
1294 " GrGLSL%s() {}\n",
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001295 baseName, baseName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001296 bool result = this->writeEmitCode(uniforms);
1297 this->write("private:\n");
1298 this->writeSetData(uniforms);
1299 this->writePrivateVars();
1300 for (const auto& u : uniforms) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001301 if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001302 this->writef(" UniformHandle %sVar;\n",
1303 HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001304 }
1305 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001306 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001307 if (needs_uniform_var(*param)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001308 this->writef(" UniformHandle %sVar;\n",
1309 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001310 }
1311 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001312 this->writef("};\n"
1313 "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
1314 " return new GrGLSL%s();\n"
1315 "}\n",
1316 fullName, baseName);
1317 this->writeGetKey();
1318 this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
1319 " const %s& that = other.cast<%s>();\n"
1320 " (void) that;\n",
1321 fullName, fullName, fullName);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001322 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001323 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001324 continue;
1325 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001326 String nameString(param->fName);
1327 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001328 this->writef(" if (%s != that.%s) return false;\n",
1329 HCodeGenerator::FieldName(name).c_str(),
1330 HCodeGenerator::FieldName(name).c_str());
1331 }
1332 this->write(" return true;\n"
1333 "}\n");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001334 this->writeClone();
Brian Salomonf7dcd762018-07-30 14:48:15 -04001335 this->writeOnTextureSampler();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001336 this->writeTest();
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001337 this->writeSection(CPP_END_SECTION);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001338
Ethan Nicholas762466e2017-06-29 10:03:38 -04001339 result &= 0 == fErrors.errorCount();
1340 return result;
1341}
1342
1343} // namespace