blob: 66b020c41120f1b150d08fc37cedfd125fd8a28d [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 Nicholas58430122020-04-14 09:54:02 -040013#include "src/sksl/SkSLSampleMatrix.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040014
Michael Ludwig92e4c7f2018-08-30 16:08:18 -040015#include <algorithm>
16
Ethan Nicholas762466e2017-06-29 10:03:38 -040017namespace SkSL {
18
19static bool needs_uniform_var(const Variable& var) {
Ethan Nicholas5f9836e2017-12-20 15:16:33 -050020 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
21 var.fType.kind() != Type::kSampler_Kind;
Ethan Nicholas762466e2017-06-29 10:03:38 -040022}
23
24CPPCodeGenerator::CPPCodeGenerator(const Context* context, const Program* program,
25 ErrorReporter* errors, String name, OutputStream* out)
John Stiles50819422020-06-18 13:00:38 -040026 : INHERITED(context, program, errors, out)
27 , fName(std::move(name))
28 , fFullName(String::printf("Gr%s", fName.c_str()))
29 , fSectionAndParameterHelper(program, *errors) {
30 fLineEnding = "\n";
Ethan Nicholas13863662019-07-29 13:05:15 -040031 fTextureFunctionOverride = "sample";
Ethan Nicholas762466e2017-06-29 10:03:38 -040032}
33
34void CPPCodeGenerator::writef(const char* s, va_list va) {
35 static constexpr int BUFFER_SIZE = 1024;
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040036 va_list copy;
37 va_copy(copy, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040038 char buffer[BUFFER_SIZE];
John Stiles50819422020-06-18 13:00:38 -040039 int length = std::vsnprintf(buffer, BUFFER_SIZE, s, va);
Ethan Nicholas762466e2017-06-29 10:03:38 -040040 if (length < BUFFER_SIZE) {
41 fOut->write(buffer, length);
42 } else {
43 std::unique_ptr<char[]> heap(new char[length + 1]);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -040044 vsprintf(heap.get(), s, copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040045 fOut->write(heap.get(), length);
46 }
z102.zhangd74f2c82018-08-10 09:08:47 +080047 va_end(copy);
Ethan Nicholas762466e2017-06-29 10:03:38 -040048}
49
50void CPPCodeGenerator::writef(const char* s, ...) {
51 va_list va;
52 va_start(va, s);
53 this->writef(s, va);
54 va_end(va);
55}
56
57void CPPCodeGenerator::writeHeader() {
58}
59
Ethan Nicholasf7b88202017-09-18 14:10:39 -040060bool CPPCodeGenerator::usesPrecisionModifiers() const {
61 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -040062}
63
Ethan Nicholasf7b88202017-09-18 14:10:39 -040064String CPPCodeGenerator::getTypeName(const Type& type) {
65 return type.name();
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040066}
Ethan Nicholasf7b88202017-09-18 14:10:39 -040067
Ethan Nicholas762466e2017-06-29 10:03:38 -040068void CPPCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
69 Precedence parentPrecedence) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040070 if (b.fOperator == Token::Kind::TK_PERCENT) {
Ethan Nicholas762466e2017-06-29 10:03:38 -040071 // need to use "%%" instead of "%" b/c the code will be inside of a printf
72 Precedence precedence = GetBinaryPrecedence(b.fOperator);
73 if (precedence >= parentPrecedence) {
74 this->write("(");
75 }
76 this->writeExpression(*b.fLeft, precedence);
77 this->write(" %% ");
78 this->writeExpression(*b.fRight, precedence);
79 if (precedence >= parentPrecedence) {
80 this->write(")");
81 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050082 } else if (b.fLeft->fKind == Expression::kNullLiteral_Kind ||
83 b.fRight->fKind == Expression::kNullLiteral_Kind) {
84 const Variable* var;
85 if (b.fLeft->fKind != Expression::kNullLiteral_Kind) {
86 SkASSERT(b.fLeft->fKind == Expression::kVariableReference_Kind);
87 var = &((VariableReference&) *b.fLeft).fVariable;
88 } else {
89 SkASSERT(b.fRight->fKind == Expression::kVariableReference_Kind);
90 var = &((VariableReference&) *b.fRight).fVariable;
91 }
92 SkASSERT(var->fType.kind() == Type::kNullable_Kind &&
93 var->fType.componentType() == *fContext.fFragmentProcessor_Type);
94 this->write("%s");
95 const char* op;
96 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -040097 case Token::Kind::TK_EQEQ:
Ethan Nicholasee1c8a72019-02-22 10:50:47 -050098 op = "<";
99 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400100 case Token::Kind::TK_NEQ:
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500101 op = ">=";
102 break;
103 default:
104 SkASSERT(false);
105 }
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400106 fFormatArgs.push_back("_outer." + String(var->fName) + "_index " + op + " 0 ? \"true\" "
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500107 ": \"false\"");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400108 } else {
109 INHERITED::writeBinaryExpression(b, parentPrecedence);
110 }
111}
112
113void CPPCodeGenerator::writeIndexExpression(const IndexExpression& i) {
114 const Expression& base = *i.fBase;
115 if (base.fKind == Expression::kVariableReference_Kind) {
116 int builtin = ((VariableReference&) base).fVariable.fModifiers.fLayout.fBuiltin;
117 if (SK_TRANSFORMEDCOORDS2D_BUILTIN == builtin) {
118 this->write("%s");
119 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700120 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400121 "index into sk_TransformedCoords2D must be an integer literal");
122 return;
123 }
124 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
Michael Ludwig9aba6252020-06-22 14:46:36 -0400125 if (index != 0) {
126 fErrors.error(i.fIndex->fOffset, "Only sk_TransformedCoords2D[0] is allowed");
127 return;
128 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400129 String name = "sk_TransformedCoords2D_" + to_string(index);
Brian Salomonbf5c0c02019-11-11 14:55:28 -0500130 fFormatArgs.push_back(name + ".c_str()");
Michael Ludwig9aba6252020-06-22 14:46:36 -0400131 if (!fAccessLocalCoordsDirectly) {
132 fAccessLocalCoordsDirectly = true;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400133 addExtraEmitCodeLine("SkString " + name +
134 " = fragBuilder->ensureCoords2D(args.fTransformedCoords[" +
Ethan Nicholas58430122020-04-14 09:54:02 -0400135 to_string(index) + "].fVaryingPoint, _outer.sampleMatrix());");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400136 }
137 return;
138 } else if (SK_TEXTURESAMPLERS_BUILTIN == builtin) {
139 this->write("%s");
140 if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700141 fErrors.error(i.fIndex->fOffset,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400142 "index into sk_TextureSamplers must be an integer literal");
143 return;
144 }
145 int64_t index = ((IntLiteral&) *i.fIndex).fValue;
146 fFormatArgs.push_back(" fragBuilder->getProgramBuilder()->samplerVariable("
Stephen Whited523a062019-06-19 13:12:46 -0400147 "args.fTexSamplers[" + to_string(index) + "])");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400148 return;
149 }
150 }
151 INHERITED::writeIndexExpression(i);
152}
153
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400154static String default_value(const Type& type) {
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500155 if (type.fName == "bool") {
156 return "false";
157 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400158 switch (type.kind()) {
159 case Type::kScalar_Kind: return "0";
160 case Type::kVector_Kind: return type.name() + "(0)";
161 case Type::kMatrix_Kind: return type.name() + "(1)";
162 default: ABORT("unsupported default_value type\n");
163 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400164}
165
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500166static String default_value(const Variable& var) {
Brian Osman495993a2018-10-16 15:45:55 -0400167 if (var.fModifiers.fLayout.fCType == SkSL::Layout::CType::kSkPMColor4f) {
Brian Osmanf28e55d2018-10-03 16:35:54 -0400168 return "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}";
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500169 }
170 return default_value(var.fType);
171}
172
Ethan Nicholas762466e2017-06-29 10:03:38 -0400173static bool is_private(const Variable& var) {
174 return !(var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
175 !(var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
176 var.fStorage == Variable::kGlobal_Storage &&
177 var.fModifiers.fLayout.fBuiltin == -1;
178}
179
Michael Ludwiga4275592018-08-31 10:52:47 -0400180static bool is_uniform_in(const Variable& var) {
181 return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
182 (var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
183 var.fType.kind() != Type::kSampler_Kind;
184}
185
Ethan Nicholasd608c092017-10-26 09:30:08 -0400186void CPPCodeGenerator::writeRuntimeValue(const Type& type, const Layout& layout,
187 const String& cppCode) {
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400188 if (type.isFloat()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400189 this->write("%f");
190 fFormatArgs.push_back(cppCode);
191 } else if (type == *fContext.fInt_Type) {
192 this->write("%d");
193 fFormatArgs.push_back(cppCode);
194 } else if (type == *fContext.fBool_Type) {
195 this->write("%s");
196 fFormatArgs.push_back("(" + cppCode + " ? \"true\" : \"false\")");
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400197 } else if (type == *fContext.fFloat2_Type || type == *fContext.fHalf2_Type) {
198 this->write(type.name() + "(%f, %f)");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400199 fFormatArgs.push_back(cppCode + ".fX");
200 fFormatArgs.push_back(cppCode + ".fY");
Ethan Nicholas82399462017-10-16 12:35:44 -0400201 } else if (type == *fContext.fFloat4_Type || type == *fContext.fHalf4_Type) {
202 this->write(type.name() + "(%f, %f, %f, %f)");
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400203 switch (layout.fCType) {
204 case Layout::CType::kSkPMColor:
205 fFormatArgs.push_back("SkGetPackedR32(" + cppCode + ") / 255.0");
206 fFormatArgs.push_back("SkGetPackedG32(" + cppCode + ") / 255.0");
207 fFormatArgs.push_back("SkGetPackedB32(" + cppCode + ") / 255.0");
208 fFormatArgs.push_back("SkGetPackedA32(" + cppCode + ") / 255.0");
209 break;
Brian Osmanf28e55d2018-10-03 16:35:54 -0400210 case Layout::CType::kSkPMColor4f:
211 fFormatArgs.push_back(cppCode + ".fR");
212 fFormatArgs.push_back(cppCode + ".fG");
213 fFormatArgs.push_back(cppCode + ".fB");
214 fFormatArgs.push_back(cppCode + ".fA");
215 break;
Mike Reedb26b4e72020-01-22 14:31:21 -0500216 case Layout::CType::kSkV4:
217 fFormatArgs.push_back(cppCode + ".x");
218 fFormatArgs.push_back(cppCode + ".y");
219 fFormatArgs.push_back(cppCode + ".z");
220 fFormatArgs.push_back(cppCode + ".w");
Brian Salomoneca66b32019-06-01 11:18:15 -0400221 break;
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400222 case Layout::CType::kSkRect: // fall through
223 case Layout::CType::kDefault:
224 fFormatArgs.push_back(cppCode + ".left()");
225 fFormatArgs.push_back(cppCode + ".top()");
226 fFormatArgs.push_back(cppCode + ".right()");
227 fFormatArgs.push_back(cppCode + ".bottom()");
228 break;
229 default:
230 SkASSERT(false);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400231 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500232 } else if (type.kind() == Type::kEnum_Kind) {
233 this->write("%d");
234 fFormatArgs.push_back("(int) " + cppCode);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400235 } else if (type == *fContext.fInt4_Type ||
236 type == *fContext.fShort4_Type ||
237 type == *fContext.fByte4_Type) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -0500238 this->write(type.name() + "(%d, %d, %d, %d)");
239 fFormatArgs.push_back(cppCode + ".left()");
240 fFormatArgs.push_back(cppCode + ".top()");
241 fFormatArgs.push_back(cppCode + ".right()");
242 fFormatArgs.push_back(cppCode + ".bottom()");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400243 } else {
Ethan Nicholas82399462017-10-16 12:35:44 -0400244 printf("unsupported runtime value type '%s'\n", String(type.fName).c_str());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400245 SkASSERT(false);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400246 }
247}
248
249void CPPCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
250 if (is_private(var)) {
Ethan Nicholasd608c092017-10-26 09:30:08 -0400251 this->writeRuntimeValue(var.fType, var.fModifiers.fLayout, var.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400252 } else {
253 this->writeExpression(value, kTopLevel_Precedence);
254 }
255}
256
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400257String CPPCodeGenerator::getSamplerHandle(const Variable& var) {
258 int samplerCount = 0;
Ethan Nicholas68990be2017-07-13 09:36:52 -0400259 for (const auto param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400260 if (&var == param) {
261 return "args.fTexSamplers[" + to_string(samplerCount) + "]";
262 }
263 if (param->fType.kind() == Type::kSampler_Kind) {
264 ++samplerCount;
265 }
266 }
267 ABORT("should have found sampler in parameters\n");
268}
269
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400270void CPPCodeGenerator::writeIntLiteral(const IntLiteral& i) {
271 this->write(to_string((int32_t) i.fValue));
272}
273
Ethan Nicholas82399462017-10-16 12:35:44 -0400274void CPPCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
275 if (fCPPMode) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400276 SkASSERT(swizzle.fComponents.size() == 1); // no support for multiple swizzle components yet
Ethan Nicholas82399462017-10-16 12:35:44 -0400277 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
278 switch (swizzle.fComponents[0]) {
279 case 0: this->write(".left()"); break;
280 case 1: this->write(".top()"); break;
281 case 2: this->write(".right()"); break;
282 case 3: this->write(".bottom()"); break;
283 }
284 } else {
285 INHERITED::writeSwizzle(swizzle);
286 }
287}
288
Ethan Nicholas762466e2017-06-29 10:03:38 -0400289void CPPCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas82399462017-10-16 12:35:44 -0400290 if (fCPPMode) {
291 this->write(ref.fVariable.fName);
292 return;
293 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400294 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
295 case SK_INCOLOR_BUILTIN:
296 this->write("%s");
Michael Ludwig231de032018-08-30 14:33:01 -0400297 // EmitArgs.fInputColor is automatically set to half4(1) if
298 // no input was specified
299 fFormatArgs.push_back(String("args.fInputColor"));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400300 break;
301 case SK_OUTCOLOR_BUILTIN:
302 this->write("%s");
303 fFormatArgs.push_back(String("args.fOutputColor"));
304 break;
Ethan Nicholascd700e92018-08-24 16:43:57 -0400305 case SK_WIDTH_BUILTIN:
306 this->write("sk_Width");
307 break;
308 case SK_HEIGHT_BUILTIN:
309 this->write("sk_Height");
310 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400311 default:
312 if (ref.fVariable.fType.kind() == Type::kSampler_Kind) {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400313 this->write("%s");
314 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerVariable(" +
Stephen Whited523a062019-06-19 13:12:46 -0400315 this->getSamplerHandle(ref.fVariable) + ")");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400316 return;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400317 }
318 if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag) {
319 this->write("%s");
320 String name = ref.fVariable.fName;
Brian Osman1cb41712017-10-19 12:54:52 -0400321 String var = String::printf("args.fUniformHandler->getUniformCStr(%sVar)",
322 HCodeGenerator::FieldName(name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400323 String code;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400324 if (ref.fVariable.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400325 code = String::printf("%sVar.isValid() ? %s : \"%s\"",
326 HCodeGenerator::FieldName(name.c_str()).c_str(),
327 var.c_str(),
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400328 default_value(ref.fVariable.fType).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400329 } else {
330 code = var;
331 }
332 fFormatArgs.push_back(code);
333 } else if (SectionAndParameterHelper::IsParameter(ref.fVariable)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700334 String name(ref.fVariable.fName);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400335 this->writeRuntimeValue(ref.fVariable.fType, ref.fVariable.fModifiers.fLayout,
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400336 String::printf("_outer.%s", name.c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400337 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700338 this->write(ref.fVariable.fName);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400339 }
340 }
341}
342
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400343void CPPCodeGenerator::writeIfStatement(const IfStatement& s) {
344 if (s.fIsStatic) {
345 this->write("@");
346 }
347 INHERITED::writeIfStatement(s);
348}
349
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400350void CPPCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
351 if (fInMain) {
352 fErrors.error(s.fOffset, "fragmentProcessor main() may not contain return statements");
353 }
354 INHERITED::writeReturnStatement(s);
355}
356
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400357void CPPCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
358 if (s.fIsStatic) {
359 this->write("@");
360 }
361 INHERITED::writeSwitchStatement(s);
362}
363
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400364void CPPCodeGenerator::writeFieldAccess(const FieldAccess& access) {
365 if (access.fBase->fType.name() == "fragmentProcessor") {
366 // Special field access on fragment processors are converted into function calls on
367 // GrFragmentProcessor's getters.
368 if (access.fBase->fKind != Expression::kVariableReference_Kind) {
369 fErrors.error(access.fBase->fOffset, "fragmentProcessor must be a reference\n");
370 return;
371 }
372
373 const Type::Field& field = fContext.fFragmentProcessor_Type->fields()[access.fFieldIndex];
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500374 const Variable& var = ((const VariableReference&) *access.fBase).fVariable;
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400375 String cppAccess = String::printf("_outer.childProcessor(_outer.%s_index).%s()",
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500376 String(var.fName).c_str(),
377 String(field.fName).c_str());
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400378
379 if (fCPPMode) {
380 this->write(cppAccess.c_str());
381 } else {
382 writeRuntimeValue(*field.fType, Layout(), cppAccess);
383 }
384 return;
385 }
386 INHERITED::writeFieldAccess(access);
387}
388
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500389int CPPCodeGenerator::getChildFPIndex(const Variable& var) const {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400390 int index = 0;
391 bool found = false;
392 for (const auto& p : fProgram) {
393 if (ProgramElement::kVar_Kind == p.fKind) {
394 const VarDeclarations& decls = (const VarDeclarations&) p;
395 for (const auto& raw : decls.fVars) {
396 const VarDeclaration& decl = (VarDeclaration&) *raw;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500397 if (decl.fVar == &var) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400398 found = true;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500399 } else if (decl.fVar->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Michael Ludwig9094f2c2018-09-07 13:44:21 -0400400 ++index;
401 }
402 }
403 }
404 if (found) {
405 break;
406 }
407 }
408 SkASSERT(found);
409 return index;
410}
411
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400412void CPPCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas13863662019-07-29 13:05:15 -0400413 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample" &&
414 c.fArguments[0]->fType.kind() != Type::Kind::kSampler_Kind) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400415 // Sanity checks that are detected by function definition in sksl_fp.inc
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400416 SkASSERT(c.fArguments.size() >= 1 && c.fArguments.size() <= 3);
Florin Malita390f9bd2019-03-04 12:25:57 -0500417 SkASSERT("fragmentProcessor" == c.fArguments[0]->fType.name() ||
418 "fragmentProcessor?" == c.fArguments[0]->fType.name());
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400419
420 // Actually fail during compilation if arguments with valid types are
Ethan Nicholas13863662019-07-29 13:05:15 -0400421 // provided that are not variable references, since sample() is a
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400422 // special function that impacts code emission.
423 if (c.fArguments[0]->fKind != Expression::kVariableReference_Kind) {
424 fErrors.error(c.fArguments[0]->fOffset,
Ethan Nicholas13863662019-07-29 13:05:15 -0400425 "sample()'s fragmentProcessor argument must be a variable reference\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400426 return;
427 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500428 const Variable& child = ((const VariableReference&) *c.fArguments[0]).fVariable;
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400429
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400430 // Start a new extra emit code section so that the emitted child processor can depend on
431 // sksl variables defined in earlier sksl code.
432 this->newExtraEmitCodeBlock();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400433
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400434 // Set to the empty string when no input color parameter should be emitted, which means this
435 // must be properly formatted with a prefixed comma when the parameter should be inserted
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400436 // into the invokeChild() parameter list.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400437 String inputArg;
John Stiles50819422020-06-18 13:00:38 -0400438 String inputColorName;
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400439 if (c.fArguments.size() > 1 && c.fArguments[1]->fType.name() == "half4") {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400440 // Use the invokeChild() variant that accepts an input color, so convert the 2nd
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400441 // argument's expression into C++ code that produces sksl stored in an SkString.
John Stilesd060c9d2020-06-08 11:44:25 -0400442 inputColorName = "_input" + to_string(c.fOffset);
443 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments[1], inputColorName));
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400444
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400445 // invokeChild() needs a char*
John Stilesd060c9d2020-06-08 11:44:25 -0400446 inputArg = ", " + inputColorName + ".c_str()";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400447 }
448
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400449 bool hasCoords = c.fArguments.back()->fType.name() == "float2";
Brian Osman5ee90ff2020-06-10 16:08:54 -0400450 SampleMatrix matrix = SampleMatrix::Make(fProgram, child);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400451 // Write the output handling after the possible input handling
Ethan Nicholas13863662019-07-29 13:05:15 -0400452 String childName = "_sample" + to_string(c.fOffset);
Brian Osman978693c2020-01-24 14:52:10 -0500453 addExtraEmitCodeLine("SkString " + childName + ";");
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400454 String coordsName;
Ethan Nicholas58430122020-04-14 09:54:02 -0400455 String matrixName;
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400456 if (hasCoords) {
457 coordsName = "_coords" + to_string(c.fOffset);
458 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), coordsName));
459 }
Ethan Nicholas58430122020-04-14 09:54:02 -0400460 if (matrix.fKind == SampleMatrix::Kind::kVariable) {
461 matrixName = "_matrix" + to_string(c.fOffset);
462 addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments.back(), matrixName));
463 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500464 if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400465 addExtraEmitCodeLine("if (_outer." + String(child.fName) + "_index >= 0) {\n ");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500466 }
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400467 if (hasCoords) {
Brian Osman978693c2020-01-24 14:52:10 -0500468 addExtraEmitCodeLine(childName + " = this->invokeChild(_outer." + String(child.fName) +
469 "_index" + inputArg + ", args, " + coordsName + ".c_str());");
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400470 } else {
Ethan Nicholas58430122020-04-14 09:54:02 -0400471 switch (matrix.fKind) {
472 case SampleMatrix::Kind::kMixed:
473 case SampleMatrix::Kind::kVariable:
474 addExtraEmitCodeLine(childName + " = this->invokeChildWithMatrix(_outer." +
475 String(child.fName) + "_index" + inputArg + ", args, " +
476 matrixName + ".c_str());");
477 break;
478 case SampleMatrix::Kind::kConstantOrUniform:
479 case SampleMatrix::Kind::kNone:
480 addExtraEmitCodeLine(childName + " = this->invokeChild(_outer." +
481 String(child.fName) + "_index" + inputArg + ", args);");
482 break;
483 }
Ethan Nicholasd4efe682019-08-29 16:10:13 -0400484 }
485
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500486 if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000487 // Null FPs are not emitted, but their output can still be referenced in dependent
Brian Osman978693c2020-01-24 14:52:10 -0500488 // expressions - thus we always fill the variable with something.
John Stilesd060c9d2020-06-08 11:44:25 -0400489 // Sampling from a null fragment processor will provide in the input color as-is. This
490 // defaults to half4(1) if no color is specified.
John Stiles50819422020-06-18 13:00:38 -0400491 if (!inputColorName.empty()) {
492 addExtraEmitCodeLine(
493 "} else {"
494 " " + childName + ".swap(" + inputColorName + ");"
495 "}");
496 } else {
497 addExtraEmitCodeLine(
498 "} else {"
499 " " + childName + " = \"half4(1)\";"
500 "}");
501 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500502 }
John Stiles50819422020-06-18 13:00:38 -0400503
Ethan Nicholas6ad52892019-05-03 13:13:42 +0000504 this->write("%s");
505 fFormatArgs.push_back(childName + ".c_str()");
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400506 return;
507 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400508 if (c.fFunction.fBuiltin) {
509 INHERITED::writeFunctionCall(c);
510 } else {
511 this->write("%s");
512 fFormatArgs.push_back((String(c.fFunction.fName) + "_name.c_str()").c_str());
513 this->write("(");
514 const char* separator = "";
515 for (const auto& arg : c.fArguments) {
516 this->write(separator);
517 separator = ", ";
518 this->writeExpression(*arg, kSequence_Precedence);
519 }
520 this->write(")");
521 }
Ethan Nicholas13863662019-07-29 13:05:15 -0400522 if (c.fFunction.fBuiltin && c.fFunction.fName == "sample") {
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400523 this->write(".%s");
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400524 SkASSERT(c.fArguments.size() >= 1);
525 SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400526 String sampler = this->getSamplerHandle(((VariableReference&) *c.fArguments[0]).fVariable);
527 fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
Greg Daniel369ee6b2019-12-02 15:30:02 -0500528 ").asString().c_str()");
Ethan Nicholasceb4d482017-07-10 15:40:20 -0400529 }
530}
531
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400532static const char* glsltype_string(const Context& context, const Type& type) {
533 if (type == *context.fFloat_Type) {
534 return "kFloat_GrSLType";
535 } else if (type == *context.fHalf_Type) {
536 return "kHalf_GrSLType";
537 } else if (type == *context.fFloat2_Type) {
538 return "kFloat2_GrSLType";
539 } else if (type == *context.fHalf2_Type) {
540 return "kHalf2_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500541 } else if (type == *context.fFloat3_Type) {
542 return "kFloat3_GrSLType";
543 } else if (type == *context.fHalf3_Type) {
544 return "kHalf3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400545 } else if (type == *context.fFloat4_Type) {
546 return "kFloat4_GrSLType";
547 } else if (type == *context.fHalf4_Type) {
548 return "kHalf4_GrSLType";
Ethan Nicholas58430122020-04-14 09:54:02 -0400549 } else if (type == *context.fFloat2x2_Type) {
550 return "kFloat2x2_GrSLType";
551 } else if (type == *context.fHalf2x2_Type) {
552 return "kHalf2x2_GrSLType";
553 } else if (type == *context.fFloat3x3_Type) {
554 return "kFloat3x3_GrSLType";
555 } else if (type == *context.fHalf3x3_Type) {
556 return "kHalf3x3_GrSLType";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400557 } else if (type == *context.fFloat4x4_Type) {
558 return "kFloat4x4_GrSLType";
559 } else if (type == *context.fHalf4x4_Type) {
560 return "kHalf4x4_GrSLType";
561 } else if (type == *context.fVoid_Type) {
562 return "kVoid_GrSLType";
Ethan Nicholas8ae1b562019-12-17 15:18:02 -0500563 } else if (type.kind() == Type::kEnum_Kind) {
564 return "int";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400565 }
566 SkASSERT(false);
567 return nullptr;
568}
569
Ethan Nicholas762466e2017-06-29 10:03:38 -0400570void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400571 const FunctionDeclaration& decl = f.fDeclaration;
Brian Osman08f986d2020-05-13 17:06:46 -0400572 if (decl.fBuiltin) {
573 return;
574 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400575 fFunctionHeader = "";
576 OutputStream* oldOut = fOut;
577 StringStream buffer;
578 fOut = &buffer;
579 if (decl.fName == "main") {
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400580 fInMain = true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400581 for (const auto& s : ((Block&) *f.fBody).fStatements) {
582 this->writeStatement(*s);
583 this->writeLine();
584 }
Ethan Nicholasf1b14642018-08-09 16:18:07 -0400585 fInMain = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400586
587 fOut = oldOut;
588 this->write(fFunctionHeader);
589 this->write(buffer.str());
590 } else {
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400591 this->addExtraEmitCodeLine("SkString " + decl.fName + "_name;");
592 String args = "const GrShaderVar " + decl.fName + "_args[] = { ";
593 const char* separator = "";
594 for (const auto& param : decl.fParameters) {
595 args += String(separator) + "GrShaderVar(\"" + param->fName + "\", " +
596 glsltype_string(fContext, param->fType) + ")";
597 separator = ", ";
598 }
599 args += "};";
600 this->addExtraEmitCodeLine(args.c_str());
601 for (const auto& s : ((Block&) *f.fBody).fStatements) {
602 this->writeStatement(*s);
603 this->writeLine();
604 }
605
606 fOut = oldOut;
607 String emit = "fragBuilder->emitFunction(";
608 emit += glsltype_string(fContext, decl.fReturnType);
609 emit += ", \"" + decl.fName + "\"";
610 emit += ", " + to_string((int64_t) decl.fParameters.size());
611 emit += ", " + decl.fName + "_args";
John Stiles50819422020-06-18 13:00:38 -0400612 emit += ",\nR\"SkSL(" + buffer.str() + ")SkSL\"";
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400613 emit += ", &" + decl.fName + "_name);";
614 this->addExtraEmitCodeLine(emit.c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400615 }
616}
617
618void CPPCodeGenerator::writeSetting(const Setting& s) {
619 static constexpr const char* kPrefix = "sk_Args.";
620 if (!strncmp(s.fName.c_str(), kPrefix, strlen(kPrefix))) {
621 const char* name = s.fName.c_str() + strlen(kPrefix);
Ethan Nicholasd608c092017-10-26 09:30:08 -0400622 this->writeRuntimeValue(s.fType, Layout(), HCodeGenerator::FieldName(name).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400623 } else {
624 this->write(s.fName.c_str());
625 }
626}
627
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400628bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
Ethan Nicholas68990be2017-07-13 09:36:52 -0400629 const Section* s = fSectionAndParameterHelper.getSection(name);
630 if (s) {
631 this->writef("%s%s", prefix, s->fText.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400632 return true;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400633 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -0400634 return false;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400635}
636
637void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
638 if (p.fKind == ProgramElement::kSection_Kind) {
639 return;
640 }
641 if (p.fKind == ProgramElement::kVar_Kind) {
642 const VarDeclarations& decls = (const VarDeclarations&) p;
643 if (!decls.fVars.size()) {
644 return;
645 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000646 const Variable& var = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400647 if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
648 -1 != var.fModifiers.fLayout.fBuiltin) {
649 return;
650 }
651 }
652 INHERITED::writeProgramElement(p);
653}
654
655void CPPCodeGenerator::addUniform(const Variable& var) {
656 if (!needs_uniform_var(var)) {
657 return;
658 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400659 if (var.fModifiers.fLayout.fWhen.fLength) {
660 this->writef(" if (%s) {\n ", String(var.fModifiers.fLayout.fWhen).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -0400661 }
Ethan Nicholas095f5b42019-08-30 11:51:41 -0400662 const char* type = glsltype_string(fContext, var.fType);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700663 String name(var.fName);
Ethan Nicholas16464c32020-04-06 13:53:05 -0400664 this->writef(" %sVar = args.fUniformHandler->addUniform(&_outer, kFragment_GrShaderFlag,"
665 " %s, \"%s\");\n", HCodeGenerator::FieldName(name.c_str()).c_str(), type,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700666 name.c_str());
Ethan Nicholasfc994162019-06-06 10:04:27 -0400667 if (var.fModifiers.fLayout.fWhen.fLength) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400668 this->write(" }\n");
669 }
670}
671
Ethan Nicholascd700e92018-08-24 16:43:57 -0400672void CPPCodeGenerator::writeInputVars() {
673}
674
Ethan Nicholas762466e2017-06-29 10:03:38 -0400675void CPPCodeGenerator::writePrivateVars() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400676 for (const auto& p : fProgram) {
677 if (ProgramElement::kVar_Kind == p.fKind) {
678 const VarDeclarations& decls = (const VarDeclarations&) p;
679 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000680 VarDeclaration& decl = (VarDeclaration&) *raw;
681 if (is_private(*decl.fVar)) {
682 if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
683 fErrors.error(decl.fOffset,
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400684 "fragmentProcessor variables must be declared 'in'");
685 return;
686 }
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500687 this->writef("%s %s = %s;\n",
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000688 HCodeGenerator::FieldType(fContext, decl.fVar->fType,
689 decl.fVar->fModifiers.fLayout).c_str(),
Ethan Nicholase9d172a2017-11-20 12:12:24 -0500690 String(decl.fVar->fName).c_str(),
691 default_value(*decl.fVar).c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400692 } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
693 // An auto-tracked uniform in variable, so add a field to hold onto the prior
694 // state. Note that tracked variables must be uniform in's and that is validated
695 // before writePrivateVars() is called.
696 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
697 SkASSERT(mapper && mapper->supportsTracking());
698
699 String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
700 // The member statement is different if the mapper reports a default value
701 if (mapper->defaultValue().size() > 0) {
702 this->writef("%s %sPrev = %s;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400703 Layout::CTypeToStr(mapper->ctype()), name.c_str(),
Michael Ludwiga4275592018-08-31 10:52:47 -0400704 mapper->defaultValue().c_str());
705 } else {
706 this->writef("%s %sPrev;\n",
Ethan Nicholas78aceb22018-08-31 16:13:58 -0400707 Layout::CTypeToStr(mapper->ctype()), name.c_str());
Michael Ludwiga4275592018-08-31 10:52:47 -0400708 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400709 }
710 }
711 }
712 }
713}
714
715void CPPCodeGenerator::writePrivateVarValues() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400716 for (const auto& p : fProgram) {
717 if (ProgramElement::kVar_Kind == p.fKind) {
718 const VarDeclarations& decls = (const VarDeclarations&) p;
719 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000720 VarDeclaration& decl = (VarDeclaration&) *raw;
721 if (is_private(*decl.fVar) && decl.fValue) {
722 this->writef("%s = ", String(decl.fVar->fName).c_str());
Ethan Nicholas82399462017-10-16 12:35:44 -0400723 fCPPMode = true;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000724 this->writeExpression(*decl.fValue, kAssignment_Precedence);
Ethan Nicholas82399462017-10-16 12:35:44 -0400725 fCPPMode = false;
726 this->write(";\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400727 }
728 }
729 }
730 }
731}
732
Ethan Nicholas82399462017-10-16 12:35:44 -0400733static bool is_accessible(const Variable& var) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -0500734 const Type& type = var.fType.nonnullable();
735 return Type::kSampler_Kind != type.kind() &&
736 Type::kOther_Kind != type.kind();
Ethan Nicholas82399462017-10-16 12:35:44 -0400737}
738
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400739void CPPCodeGenerator::newExtraEmitCodeBlock() {
740 // This should only be called when emitting SKSL for emitCode(), which can be detected if the
741 // cpp buffer is not null, and the cpp buffer is not the current output.
742 SkASSERT(fCPPBuffer && fCPPBuffer != fOut);
743
744 // Start a new block as an empty string
745 fExtraEmitCodeBlocks.push_back("");
746 // Mark its location in the output buffer, uses ${\d} for the token since ${} will not occur in
747 // valid sksl and makes detection trivial.
748 this->writef("${%zu}", fExtraEmitCodeBlocks.size() - 1);
749}
750
751void CPPCodeGenerator::addExtraEmitCodeLine(const String& toAppend) {
752 SkASSERT(fExtraEmitCodeBlocks.size() > 0);
753 String& currentBlock = fExtraEmitCodeBlocks[fExtraEmitCodeBlocks.size() - 1];
754 // Automatically add indentation and newline
755 currentBlock += " " + toAppend + "\n";
756}
757
758void CPPCodeGenerator::flushEmittedCode() {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400759 if (fCPPBuffer == nullptr) {
760 // Not actually within writeEmitCode() so nothing to flush
761 return;
762 }
763
764 StringStream* skslBuffer = static_cast<StringStream*>(fOut);
765
766 String sksl = skslBuffer->str();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400767 // Empty the accumulation buffer since its current contents are consumed.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400768 skslBuffer->reset();
769
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400770 // Switch to the cpp buffer
Michael Ludwigd0440192018-09-07 14:24:52 +0000771 fOut = fCPPBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400772
773 // Iterate through the sksl, keeping track of where the last statement ended (e.g. the latest
774 // encountered ';', '{', or '}'). If an extra emit code block token is encountered then the
775 // code from 0 to last statement end is sent to writeCodeAppend, the extra code block is
776 // appended to the cpp buffer, and then the sksl string is trimmed to start where the last
777 // statement left off (minus the encountered token).
778 size_t i = 0;
779 int flushPoint = -1;
780 int tokenStart = -1;
781 while (i < sksl.size()) {
782 if (tokenStart >= 0) {
783 // Looking for the end of the token
784 if (sksl[i] == '}') {
785 // Must append the sksl from 0 to flushPoint (inclusive) then the extra code
786 // accumulated in the block with index parsed from chars [tokenStart+2, i-1]
787 String toFlush = String(sksl.c_str(), flushPoint + 1);
788 // writeCodeAppend automatically removes the format args that it consumed, so
789 // fFormatArgs will be in a valid state for any future sksl
790 this->writeCodeAppend(toFlush);
791
792 int codeBlock = stoi(String(sksl.c_str() + tokenStart + 2, i - tokenStart - 2));
793 SkASSERT(codeBlock < (int) fExtraEmitCodeBlocks.size());
794 if (fExtraEmitCodeBlocks[codeBlock].size() > 0) {
795 this->write(fExtraEmitCodeBlocks[codeBlock].c_str());
796 }
797
798 // Now reset the sksl buffer to start after the flush point, but remove the token.
799 String compacted = String(sksl.c_str() + flushPoint + 1,
800 tokenStart - flushPoint - 1);
801 if (i < sksl.size() - 1) {
802 compacted += String(sksl.c_str() + i + 1, sksl.size() - i - 1);
803 }
804 sksl = compacted;
805
806 // And reset iteration
807 i = -1;
808 flushPoint = -1;
809 tokenStart = -1;
810 }
811 } else {
812 // Looking for the start of extra emit block tokens, and tracking when statements end
813 if (sksl[i] == ';' || sksl[i] == '{' || sksl[i] == '}') {
814 flushPoint = i;
815 } else if (i < sksl.size() - 1 && sksl[i] == '$' && sksl[i + 1] == '{') {
816 // found an extra emit code block token
817 tokenStart = i++;
818 }
819 }
820 i++;
Michael Ludwigd0440192018-09-07 14:24:52 +0000821 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400822
823 // Once we've gone through the sksl string to this point, there are no remaining extra emit
824 // code blocks to interleave, so append the remainder as usual.
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400825 this->writeCodeAppend(sksl);
826
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400827 // After appending, switch back to the emptied sksl buffer and reset the extra code blocks
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400828 fOut = skslBuffer;
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400829 fExtraEmitCodeBlocks.clear();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400830}
831
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400832void CPPCodeGenerator::writeCodeAppend(const String& code) {
John Stiles50819422020-06-18 13:00:38 -0400833 if (!code.empty()) {
834 // Count % format specifiers.
835 size_t argCount = 0;
836 for (size_t index = 0; index < code.size(); ++index) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400837 if ('%' == code[index]) {
John Stiles50819422020-06-18 13:00:38 -0400838 if (index == code.size() - 1) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400839 break;
840 }
841 if (code[index + 1] != '%') {
842 ++argCount;
843 }
844 }
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400845 }
John Stiles50819422020-06-18 13:00:38 -0400846
847 // Emit the code string.
848 this->writef(" fragBuilder->codeAppendf(\n"
849 "R\"SkSL(%s)SkSL\"\n", code.c_str());
850 for (size_t i = 0; i < argCount; ++i) {
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400851 this->writef(", %s", fFormatArgs[i].c_str());
852 }
853 this->write(");\n");
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400854
John Stiles50819422020-06-18 13:00:38 -0400855 // argCount is equal to the number of fFormatArgs that were consumed, so they should be
856 // removed from the list.
857 if (argCount > 0) {
858 fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argCount);
859 }
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400860 }
861}
862
863String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
864 const String& cppVar) {
865 // To do this conversion, we temporarily switch the sksl output stream
866 // to an empty stringstream and reset the format args to empty.
867 OutputStream* oldSKSL = fOut;
868 StringStream exprBuffer;
869 fOut = &exprBuffer;
870
871 std::vector<String> oldArgs(fFormatArgs);
872 fFormatArgs.clear();
873
874 // Convert the argument expression into a format string and args
875 this->writeExpression(e, Precedence::kTopLevel_Precedence);
876 std::vector<String> newArgs(fFormatArgs);
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400877 String expr = exprBuffer.str();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400878
879 // After generating, restore the original output stream and format args
880 fFormatArgs = oldArgs;
881 fOut = oldSKSL;
882
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400883 // The sksl written to exprBuffer is not processed by flushEmittedCode(), so any extra emit code
884 // block tokens won't get handled. So we need to strip them from the expression and stick them
885 // to the end of the original sksl stream.
886 String exprFormat = "";
887 int tokenStart = -1;
888 for (size_t i = 0; i < expr.size(); i++) {
889 if (tokenStart >= 0) {
890 if (expr[i] == '}') {
891 // End of the token, so append the token to fOut
892 fOut->write(expr.c_str() + tokenStart, i - tokenStart + 1);
893 tokenStart = -1;
894 }
895 } else {
896 if (i < expr.size() - 1 && expr[i] == '$' && expr[i + 1] == '{') {
897 tokenStart = i++;
898 } else {
899 exprFormat += expr[i];
900 }
901 }
902 }
903
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400904 // Now build the final C++ code snippet from the format string and args
905 String cppExpr;
John Stiles50819422020-06-18 13:00:38 -0400906 if (newArgs.empty()) {
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400907 // This was a static expression, so we can simplify the input
908 // color declaration in the emitted code to just a static string
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400909 cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");";
John Stiles50819422020-06-18 13:00:38 -0400910 } else if (newArgs.size() == 1 && exprFormat == "%s") {
911 // If the format expression is simply "%s", we can avoid an expensive call to printf.
912 // This happens fairly often in codegen so it is worth simplifying.
913 cppExpr = "SkString " + cppVar + "(" + newArgs[0] + ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400914 } else {
915 // String formatting must occur dynamically, so have the C++ declaration
916 // use SkStringPrintf with the format args that were accumulated
917 // when the expression was written.
918 cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
919 for (size_t i = 0; i < newArgs.size(); i++) {
920 cppExpr += ", " + newArgs[i];
921 }
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400922 cppExpr += ");";
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400923 }
924 return cppExpr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400925}
926
Ethan Nicholas762466e2017-06-29 10:03:38 -0400927bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
928 this->write(" void emitCode(EmitArgs& args) override {\n"
929 " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
930 this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
931 " (void) _outer;\n",
932 fFullName.c_str(), fFullName.c_str());
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400933 for (const auto& p : fProgram) {
934 if (ProgramElement::kVar_Kind == p.fKind) {
935 const VarDeclarations& decls = (const VarDeclarations&) p;
936 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000937 VarDeclaration& decl = (VarDeclaration&) *raw;
938 String nameString(decl.fVar->fName);
Ethan Nicholas82399462017-10-16 12:35:44 -0400939 const char* name = nameString.c_str();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000940 if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
941 is_accessible(*decl.fVar)) {
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400942 this->writef(" auto %s = _outer.%s;\n"
Ethan Nicholas82399462017-10-16 12:35:44 -0400943 " (void) %s;\n",
944 name, name, name);
945 }
946 }
947 }
948 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400949 this->writePrivateVarValues();
950 for (const auto u : uniforms) {
951 this->addUniform(*u);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400952 }
953 this->writeSection(EMIT_CODE_SECTION);
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400954
955 // Save original buffer as the CPP buffer for flushEmittedCode()
956 fCPPBuffer = fOut;
957 StringStream skslBuffer;
958 fOut = &skslBuffer;
959
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400960 this->newExtraEmitCodeBlock();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400961 bool result = INHERITED::generateCode();
Michael Ludwig1fc5fbd2018-09-07 13:13:06 -0400962 this->flushEmittedCode();
Michael Ludwig92e4c7f2018-08-30 16:08:18 -0400963
964 // Then restore the original CPP buffer and close the function
965 fOut = fCPPBuffer;
966 fCPPBuffer = nullptr;
Ethan Nicholas5b6e6272017-10-13 13:11:06 -0400967 this->write(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -0400968 return result;
969}
970
971void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
972 const char* fullName = fFullName.c_str();
Ethan Nicholas68990be2017-07-13 09:36:52 -0400973 const Section* section = fSectionAndParameterHelper.getSection(SET_DATA_SECTION);
974 const char* pdman = section ? section->fArgument.c_str() : "pdman";
Ethan Nicholas762466e2017-06-29 10:03:38 -0400975 this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
976 "const GrFragmentProcessor& _proc) override {\n",
977 pdman);
978 bool wroteProcessor = false;
John Stiles06f3d082020-06-04 11:07:21 -0400979 for (const Variable* u : uniforms) {
Michael Ludwiga4275592018-08-31 10:52:47 -0400980 if (is_uniform_in(*u)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400981 if (!wroteProcessor) {
982 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
983 wroteProcessor = true;
984 this->writef(" {\n");
985 }
Michael Ludwiga4275592018-08-31 10:52:47 -0400986
987 const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
988 SkASSERT(mapper);
989
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700990 String nameString(u->fName);
991 const char* name = nameString.c_str();
Michael Ludwiga4275592018-08-31 10:52:47 -0400992
993 // Switches for setData behavior in the generated code
994 bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
995 bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
996 bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
997
998 String uniformName = HCodeGenerator::FieldName(name) + "Var";
999
1000 String indent = " "; // 8 by default, 12 when nested for conditional uniforms
1001 if (conditionalUniform) {
1002 // Add a pre-check to make sure the uniform was emitted
1003 // before trying to send any data to the GPU
1004 this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
1005 indent += " ";
1006 }
1007
1008 String valueVar = "";
1009 if (needsValueDeclaration) {
1010 valueVar.appendf("%sValue", name);
1011 // Use AccessType since that will match the return type of _outer's public API.
1012 String valueType = HCodeGenerator::AccessType(fContext, u->fType,
1013 u->fModifiers.fLayout);
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001014 this->writef("%s%s %s = _outer.%s;\n",
Michael Ludwiga4275592018-08-31 10:52:47 -04001015 indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001016 } else {
Michael Ludwiga4275592018-08-31 10:52:47 -04001017 // Not tracked and the mapper only needs to use the value once
1018 // so send it a safe expression instead of the variable name
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001019 valueVar.appendf("(_outer.%s)", name);
Michael Ludwiga4275592018-08-31 10:52:47 -04001020 }
1021
1022 if (isTracked) {
1023 SkASSERT(mapper->supportsTracking());
1024
1025 String prevVar = HCodeGenerator::FieldName(name) + "Prev";
1026 this->writef("%sif (%s) {\n"
1027 "%s %s;\n"
1028 "%s %s;\n"
1029 "%s}\n", indent.c_str(),
1030 mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
1031 mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
1032 mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
1033 } else {
1034 this->writef("%s%s;\n", indent.c_str(),
1035 mapper->setUniform(pdman, uniformName, valueVar).c_str());
1036 }
1037
1038 if (conditionalUniform) {
1039 // Close the earlier precheck block
1040 this->writef(" }\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001041 }
1042 }
1043 }
1044 if (wroteProcessor) {
1045 this->writef(" }\n");
1046 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001047 if (section) {
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001048 int samplerIndex = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001049 for (const auto& p : fProgram) {
1050 if (ProgramElement::kVar_Kind == p.fKind) {
1051 const VarDeclarations& decls = (const VarDeclarations&) p;
John Stiles06f3d082020-06-04 11:07:21 -04001052 for (const std::unique_ptr<Statement>& raw : decls.fVars) {
1053 const VarDeclaration& decl = static_cast<VarDeclaration&>(*raw);
1054 const Variable& variable = *decl.fVar;
1055 String nameString(variable.fName);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001056 const char* name = nameString.c_str();
John Stiles06f3d082020-06-04 11:07:21 -04001057 if (variable.fType.kind() == Type::kSampler_Kind) {
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001058 this->writef(" const GrSurfaceProxyView& %sView = "
1059 "_outer.textureSampler(%d).view();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001060 name, samplerIndex);
Robert Phillipsbd99c0c2019-12-12 13:26:58 +00001061 this->writef(" GrTexture& %s = *%sView.proxy()->peekTexture();\n",
Ethan Nicholas2d5f9b32017-12-13 14:36:14 -05001062 name, name);
1063 this->writef(" (void) %s;\n", name);
1064 ++samplerIndex;
John Stiles06f3d082020-06-04 11:07:21 -04001065 } else if (needs_uniform_var(variable)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001066 this->writef(" UniformHandle& %s = %sVar;\n"
1067 " (void) %s;\n",
1068 name, HCodeGenerator::FieldName(name).c_str(), name);
John Stiles06f3d082020-06-04 11:07:21 -04001069 } else if (SectionAndParameterHelper::IsParameter(variable) &&
1070 variable.fType != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001071 if (!wroteProcessor) {
1072 this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
1073 fullName);
1074 wroteProcessor = true;
1075 }
John Stiles06f3d082020-06-04 11:07:21 -04001076
1077 if (variable.fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
1078 this->writef(" auto %s = _outer.%s;\n"
1079 " (void) %s;\n",
1080 name, name, name);
1081 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001082 }
1083 }
1084 }
1085 }
1086 this->writeSection(SET_DATA_SECTION);
1087 }
1088 this->write(" }\n");
1089}
1090
Brian Salomonf7dcd762018-07-30 14:48:15 -04001091void CPPCodeGenerator::writeOnTextureSampler() {
1092 bool foundSampler = false;
1093 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1094 if (param->fType.kind() == Type::kSampler_Kind) {
1095 if (!foundSampler) {
1096 this->writef(
1097 "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
1098 "index) const {\n",
1099 fFullName.c_str());
1100 this->writef(" return IthTextureSampler(index, %s",
1101 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1102 foundSampler = true;
1103 } else {
1104 this->writef(", %s",
1105 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
1106 }
1107 }
1108 }
1109 if (foundSampler) {
1110 this->write(");\n}\n");
1111 }
1112}
1113
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001114void CPPCodeGenerator::writeClone() {
1115 if (!this->writeSection(CLONE_SECTION)) {
1116 if (fSectionAndParameterHelper.getSection(FIELDS_SECTION)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001117 fErrors.error(0, "fragment processors with custom @fields must also have a custom"
1118 "@clone");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001119 }
1120 this->writef("%s::%s(const %s& src)\n"
Ethan Nicholasabff9562017-10-09 10:54:08 -04001121 ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
1122 fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001123 const auto transforms = fSectionAndParameterHelper.getSections(COORD_TRANSFORM_SECTION);
1124 for (size_t i = 0; i < transforms.size(); ++i) {
1125 const Section& s = *transforms[i];
1126 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
1127 this->writef("\n, %s(src.%s)", fieldName.c_str(), fieldName.c_str());
1128 }
John Stiles06f3d082020-06-04 11:07:21 -04001129 for (const Variable* param : fSectionAndParameterHelper.getParameters()) {
Robert Phillipsbce7d862019-02-21 22:53:57 +00001130 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
John Stiles88183902020-06-10 16:40:38 -04001131 if (param->fType.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001132 this->writef("\n, %s(src.%s)",
1133 fieldName.c_str(),
1134 fieldName.c_str());
1135 }
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001136 }
Ethan Nicholasabff9562017-10-09 10:54:08 -04001137 this->writef(" {\n");
Brian Salomonf7dcd762018-07-30 14:48:15 -04001138 int samplerCount = 0;
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001139 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
1140 if (param->fType.kind() == Type::kSampler_Kind) {
Brian Salomonf7dcd762018-07-30 14:48:15 -04001141 ++samplerCount;
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001142 } else if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
1143 String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
1144 if (param->fType.kind() == Type::kNullable_Kind) {
John Stiles88183902020-06-10 16:40:38 -04001145 this->writef(" if (src.%s_index >= 0) {\n", fieldName.c_str());
Brian Salomonb243b432020-02-20 14:41:47 -05001146 } else {
1147 this->write(" {\n");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001148 }
John Stiles3779f442020-06-15 10:48:49 -04001149 this->writef(" %s_index = this->cloneAndRegisterChildProcessor("
1150 "src.childProcessor(src.%s_index));\n"
1151 " }\n",
1152 fieldName.c_str(), fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001153 }
1154 }
Brian Salomonf7dcd762018-07-30 14:48:15 -04001155 if (samplerCount) {
1156 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
1157 }
Ethan Nicholas929a6812018-08-06 14:56:59 -04001158 for (size_t i = 0; i < transforms.size(); ++i) {
1159 const Section& s = *transforms[i];
1160 String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
1161 this->writef(" this->addCoordTransform(&%s);\n", fieldName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001162 }
1163 this->write("}\n");
Brian Salomonaff329b2017-08-11 09:40:37 -04001164 this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
1165 fFullName.c_str());
1166 this->writef(" return std::unique_ptr<GrFragmentProcessor>(new %s(*this));\n",
1167 fFullName.c_str());
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001168 this->write("}\n");
1169 }
1170}
1171
Ethan Nicholas762466e2017-06-29 10:03:38 -04001172void CPPCodeGenerator::writeTest() {
Ethan Nicholas68990be2017-07-13 09:36:52 -04001173 const Section* test = fSectionAndParameterHelper.getSection(TEST_CODE_SECTION);
1174 if (test) {
Brian Salomonaff329b2017-08-11 09:40:37 -04001175 this->writef(
1176 "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
1177 "#if GR_TEST_UTILS\n"
1178 "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
1179 fFullName.c_str(),
1180 fFullName.c_str(),
1181 test->fArgument.c_str());
Ethan Nicholas68990be2017-07-13 09:36:52 -04001182 this->writeSection(TEST_CODE_SECTION);
1183 this->write("}\n"
1184 "#endif\n");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001185 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001186}
1187
1188void CPPCodeGenerator::writeGetKey() {
1189 this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
1190 "GrProcessorKeyBuilder* b) const {\n",
1191 fFullName.c_str());
Ethan Nicholascab767f2019-07-01 13:32:07 -04001192 for (const auto& p : fProgram) {
1193 if (ProgramElement::kVar_Kind == p.fKind) {
1194 const VarDeclarations& decls = (const VarDeclarations&) p;
1195 for (const auto& raw : decls.fVars) {
1196 const VarDeclaration& decl = (VarDeclaration&) *raw;
1197 const Variable& var = *decl.fVar;
1198 String nameString(var.fName);
1199 const char* name = nameString.c_str();
1200 if (var.fModifiers.fLayout.fKey != Layout::kNo_Key &&
1201 (var.fModifiers.fFlags & Modifiers::kUniform_Flag)) {
1202 fErrors.error(var.fOffset,
1203 "layout(key) may not be specified on uniforms");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -04001204 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001205 switch (var.fModifiers.fLayout.fKey) {
1206 case Layout::kKey_Key:
1207 if (is_private(var)) {
1208 this->writef("%s %s =",
1209 HCodeGenerator::FieldType(fContext, var.fType,
1210 var.fModifiers.fLayout).c_str(),
1211 String(var.fName).c_str());
1212 if (decl.fValue) {
1213 fCPPMode = true;
1214 this->writeExpression(*decl.fValue, kAssignment_Precedence);
1215 fCPPMode = false;
1216 } else {
1217 this->writef("%s", default_value(var).c_str());
1218 }
1219 this->write(";\n");
1220 }
1221 if (var.fModifiers.fLayout.fWhen.fLength) {
1222 this->writef("if (%s) {", String(var.fModifiers.fLayout.fWhen).c_str());
1223 }
1224 if (var.fType == *fContext.fFloat4x4_Type) {
1225 ABORT("no automatic key handling for float4x4\n");
1226 } else if (var.fType == *fContext.fFloat2_Type) {
1227 this->writef(" b->add32(%s.fX);\n",
1228 HCodeGenerator::FieldName(name).c_str());
1229 this->writef(" b->add32(%s.fY);\n",
1230 HCodeGenerator::FieldName(name).c_str());
1231 } else if (var.fType == *fContext.fFloat4_Type) {
1232 this->writef(" b->add32(%s.x());\n",
1233 HCodeGenerator::FieldName(name).c_str());
1234 this->writef(" b->add32(%s.y());\n",
1235 HCodeGenerator::FieldName(name).c_str());
1236 this->writef(" b->add32(%s.width());\n",
1237 HCodeGenerator::FieldName(name).c_str());
1238 this->writef(" b->add32(%s.height());\n",
1239 HCodeGenerator::FieldName(name).c_str());
1240 } else if (var.fType == *fContext.fHalf4_Type) {
1241 this->writef(" uint16_t red = SkFloatToHalf(%s.fR);\n",
1242 HCodeGenerator::FieldName(name).c_str());
1243 this->writef(" uint16_t green = SkFloatToHalf(%s.fG);\n",
1244 HCodeGenerator::FieldName(name).c_str());
1245 this->writef(" uint16_t blue = SkFloatToHalf(%s.fB);\n",
1246 HCodeGenerator::FieldName(name).c_str());
1247 this->writef(" uint16_t alpha = SkFloatToHalf(%s.fA);\n",
1248 HCodeGenerator::FieldName(name).c_str());
1249 this->write(" b->add32(((uint32_t)red << 16) | green);\n");
1250 this->write(" b->add32(((uint32_t)blue << 16) | alpha);\n");
1251 } else {
1252 this->writef(" b->add32((int32_t) %s);\n",
1253 HCodeGenerator::FieldName(name).c_str());
1254 }
1255 if (var.fModifiers.fLayout.fWhen.fLength) {
1256 this->write("}");
1257 }
1258 break;
1259 case Layout::kIdentity_Key:
1260 if (var.fType.kind() != Type::kMatrix_Kind) {
1261 fErrors.error(var.fOffset,
1262 "layout(key=identity) requires matrix type");
1263 }
1264 this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
1265 HCodeGenerator::FieldName(name).c_str());
1266 break;
1267 case Layout::kNo_Key:
1268 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001269 }
Ethan Nicholascab767f2019-07-01 13:32:07 -04001270 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001271 }
1272 }
1273 this->write("}\n");
1274}
1275
1276bool CPPCodeGenerator::generateCode() {
1277 std::vector<const Variable*> uniforms;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001278 for (const auto& p : fProgram) {
1279 if (ProgramElement::kVar_Kind == p.fKind) {
1280 const VarDeclarations& decls = (const VarDeclarations&) p;
1281 for (const auto& raw : decls.fVars) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001282 VarDeclaration& decl = (VarDeclaration&) *raw;
1283 if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1284 decl.fVar->fType.kind() != Type::kSampler_Kind) {
1285 uniforms.push_back(decl.fVar);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001286 }
Michael Ludwiga4275592018-08-31 10:52:47 -04001287
1288 if (is_uniform_in(*decl.fVar)) {
1289 // Validate the "uniform in" declarations to make sure they are fully supported,
1290 // instead of generating surprising C++
1291 const UniformCTypeMapper* mapper =
1292 UniformCTypeMapper::Get(fContext, *decl.fVar);
1293 if (mapper == nullptr) {
1294 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1295 + "'s type is not supported for use as a 'uniform in'");
1296 return false;
1297 }
1298 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1299 if (!mapper->supportsTracking()) {
1300 fErrors.error(decl.fOffset, String(decl.fVar->fName)
1301 + "'s type does not support state tracking");
1302 return false;
1303 }
1304 }
1305
1306 } else {
1307 // If it's not a uniform_in, it's an error to be tracked
1308 if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
1309 fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
1310 return false;
1311 }
1312 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001313 }
1314 }
1315 }
1316 const char* baseName = fName.c_str();
1317 const char* fullName = fFullName.c_str();
Ethan Nicholas130fb3f2018-02-01 12:14:34 -05001318 this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001319 this->writef(kFragmentProcessorHeader, fullName);
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001320 this->writef("#include \"%s.h\"\n\n", fullName);
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001321 this->writeSection(CPP_SECTION);
Greg Daniel456f9b52020-03-05 19:14:18 +00001322 this->writef("#include \"src/gpu/GrTexture.h\"\n"
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001323 "#include \"src/gpu/glsl/GrGLSLFragmentProcessor.h\"\n"
1324 "#include \"src/gpu/glsl/GrGLSLFragmentShaderBuilder.h\"\n"
1325 "#include \"src/gpu/glsl/GrGLSLProgramBuilder.h\"\n"
1326 "#include \"src/sksl/SkSLCPP.h\"\n"
1327 "#include \"src/sksl/SkSLUtil.h\"\n"
Ethan Nicholas762466e2017-06-29 10:03:38 -04001328 "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
1329 "public:\n"
1330 " GrGLSL%s() {}\n",
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001331 baseName, baseName);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001332 bool result = this->writeEmitCode(uniforms);
1333 this->write("private:\n");
1334 this->writeSetData(uniforms);
1335 this->writePrivateVars();
1336 for (const auto& u : uniforms) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001337 if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001338 this->writef(" UniformHandle %sVar;\n",
1339 HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001340 }
1341 }
Ethan Nicholas68990be2017-07-13 09:36:52 -04001342 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001343 if (needs_uniform_var(*param)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001344 this->writef(" UniformHandle %sVar;\n",
1345 HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
Ethan Nicholas762466e2017-06-29 10:03:38 -04001346 }
1347 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001348 this->writef("};\n"
1349 "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
1350 " return new GrGLSL%s();\n"
1351 "}\n",
1352 fullName, baseName);
1353 this->writeGetKey();
1354 this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
1355 " const %s& that = other.cast<%s>();\n"
1356 " (void) that;\n",
1357 fullName, fullName, fullName);
Ethan Nicholas68990be2017-07-13 09:36:52 -04001358 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001359 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001360 continue;
1361 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001362 String nameString(param->fName);
1363 const char* name = nameString.c_str();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001364 this->writef(" if (%s != that.%s) return false;\n",
1365 HCodeGenerator::FieldName(name).c_str(),
1366 HCodeGenerator::FieldName(name).c_str());
1367 }
1368 this->write(" return true;\n"
1369 "}\n");
Ethan Nicholasf57c0d62017-07-31 11:18:22 -04001370 this->writeClone();
Brian Salomonf7dcd762018-07-30 14:48:15 -04001371 this->writeOnTextureSampler();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001372 this->writeTest();
Ethan Nicholas9fb036f2017-07-05 16:19:09 -04001373 this->writeSection(CPP_END_SECTION);
Greg Daniel3e8c3452018-04-06 10:37:55 -04001374
Ethan Nicholas762466e2017-06-29 10:03:38 -04001375 result &= 0 == fErrors.errorCount();
1376 return result;
1377}
1378
1379} // namespace