SkSLCPPCodeGenerator.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. /*
  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. #include "src/sksl/SkSLCPPCodeGenerator.h"
  8. #include "src/sksl/SkSLCPPUniformCTypes.h"
  9. #include "src/sksl/SkSLCompiler.h"
  10. #include "src/sksl/SkSLHCodeGenerator.h"
  11. #include <algorithm>
  12. namespace SkSL {
  13. static bool needs_uniform_var(const Variable& var) {
  14. return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
  15. var.fType.kind() != Type::kSampler_Kind;
  16. }
  17. CPPCodeGenerator::CPPCodeGenerator(const Context* context, const Program* program,
  18. ErrorReporter* errors, String name, OutputStream* out)
  19. : INHERITED(context, program, errors, out)
  20. , fName(std::move(name))
  21. , fFullName(String::printf("Gr%s", fName.c_str()))
  22. , fSectionAndParameterHelper(*program, *errors) {
  23. fLineEnding = "\\n";
  24. }
  25. void CPPCodeGenerator::writef(const char* s, va_list va) {
  26. static constexpr int BUFFER_SIZE = 1024;
  27. va_list copy;
  28. va_copy(copy, va);
  29. char buffer[BUFFER_SIZE];
  30. int length = vsnprintf(buffer, BUFFER_SIZE, s, va);
  31. if (length < BUFFER_SIZE) {
  32. fOut->write(buffer, length);
  33. } else {
  34. std::unique_ptr<char[]> heap(new char[length + 1]);
  35. vsprintf(heap.get(), s, copy);
  36. fOut->write(heap.get(), length);
  37. }
  38. va_end(copy);
  39. }
  40. void CPPCodeGenerator::writef(const char* s, ...) {
  41. va_list va;
  42. va_start(va, s);
  43. this->writef(s, va);
  44. va_end(va);
  45. }
  46. void CPPCodeGenerator::writeHeader() {
  47. }
  48. bool CPPCodeGenerator::usesPrecisionModifiers() const {
  49. return false;
  50. }
  51. String CPPCodeGenerator::getTypeName(const Type& type) {
  52. return type.name();
  53. }
  54. void CPPCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
  55. Precedence parentPrecedence) {
  56. if (b.fOperator == Token::PERCENT) {
  57. // need to use "%%" instead of "%" b/c the code will be inside of a printf
  58. Precedence precedence = GetBinaryPrecedence(b.fOperator);
  59. if (precedence >= parentPrecedence) {
  60. this->write("(");
  61. }
  62. this->writeExpression(*b.fLeft, precedence);
  63. this->write(" %% ");
  64. this->writeExpression(*b.fRight, precedence);
  65. if (precedence >= parentPrecedence) {
  66. this->write(")");
  67. }
  68. } else if (b.fLeft->fKind == Expression::kNullLiteral_Kind ||
  69. b.fRight->fKind == Expression::kNullLiteral_Kind) {
  70. const Variable* var;
  71. if (b.fLeft->fKind != Expression::kNullLiteral_Kind) {
  72. SkASSERT(b.fLeft->fKind == Expression::kVariableReference_Kind);
  73. var = &((VariableReference&) *b.fLeft).fVariable;
  74. } else {
  75. SkASSERT(b.fRight->fKind == Expression::kVariableReference_Kind);
  76. var = &((VariableReference&) *b.fRight).fVariable;
  77. }
  78. SkASSERT(var->fType.kind() == Type::kNullable_Kind &&
  79. var->fType.componentType() == *fContext.fFragmentProcessor_Type);
  80. this->write("%s");
  81. const char* op;
  82. switch (b.fOperator) {
  83. case Token::EQEQ:
  84. op = "<";
  85. break;
  86. case Token::NEQ:
  87. op = ">=";
  88. break;
  89. default:
  90. SkASSERT(false);
  91. }
  92. fFormatArgs.push_back("_outer." + String(var->fName) + "_index " + op + " 0 ? \"true\" "
  93. ": \"false\"");
  94. } else {
  95. INHERITED::writeBinaryExpression(b, parentPrecedence);
  96. }
  97. }
  98. void CPPCodeGenerator::writeIndexExpression(const IndexExpression& i) {
  99. const Expression& base = *i.fBase;
  100. if (base.fKind == Expression::kVariableReference_Kind) {
  101. int builtin = ((VariableReference&) base).fVariable.fModifiers.fLayout.fBuiltin;
  102. if (SK_TRANSFORMEDCOORDS2D_BUILTIN == builtin) {
  103. this->write("%s");
  104. if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
  105. fErrors.error(i.fIndex->fOffset,
  106. "index into sk_TransformedCoords2D must be an integer literal");
  107. return;
  108. }
  109. int64_t index = ((IntLiteral&) *i.fIndex).fValue;
  110. String name = "sk_TransformedCoords2D_" + to_string(index);
  111. fFormatArgs.push_back(name + ".c_str()");
  112. if (fWrittenTransformedCoords.find(index) == fWrittenTransformedCoords.end()) {
  113. addExtraEmitCodeLine("SkString " + name +
  114. " = fragBuilder->ensureCoords2D(args.fTransformedCoords[" +
  115. to_string(index) + "]);");
  116. fWrittenTransformedCoords.insert(index);
  117. }
  118. return;
  119. } else if (SK_TEXTURESAMPLERS_BUILTIN == builtin) {
  120. this->write("%s");
  121. if (i.fIndex->fKind != Expression::kIntLiteral_Kind) {
  122. fErrors.error(i.fIndex->fOffset,
  123. "index into sk_TextureSamplers must be an integer literal");
  124. return;
  125. }
  126. int64_t index = ((IntLiteral&) *i.fIndex).fValue;
  127. fFormatArgs.push_back(" fragBuilder->getProgramBuilder()->samplerVariable("
  128. "args.fTexSamplers[" + to_string(index) + "])");
  129. return;
  130. }
  131. }
  132. INHERITED::writeIndexExpression(i);
  133. }
  134. static String default_value(const Type& type) {
  135. if (type.fName == "bool") {
  136. return "false";
  137. }
  138. switch (type.kind()) {
  139. case Type::kScalar_Kind: return "0";
  140. case Type::kVector_Kind: return type.name() + "(0)";
  141. case Type::kMatrix_Kind: return type.name() + "(1)";
  142. default: ABORT("unsupported default_value type\n");
  143. }
  144. }
  145. static String default_value(const Variable& var) {
  146. if (var.fModifiers.fLayout.fCType == SkSL::Layout::CType::kSkPMColor4f) {
  147. return "{SK_FloatNaN, SK_FloatNaN, SK_FloatNaN, SK_FloatNaN}";
  148. }
  149. return default_value(var.fType);
  150. }
  151. static bool is_private(const Variable& var) {
  152. return !(var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
  153. !(var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
  154. var.fStorage == Variable::kGlobal_Storage &&
  155. var.fModifiers.fLayout.fBuiltin == -1;
  156. }
  157. static bool is_uniform_in(const Variable& var) {
  158. return (var.fModifiers.fFlags & Modifiers::kUniform_Flag) &&
  159. (var.fModifiers.fFlags & Modifiers::kIn_Flag) &&
  160. var.fType.kind() != Type::kSampler_Kind;
  161. }
  162. void CPPCodeGenerator::writeRuntimeValue(const Type& type, const Layout& layout,
  163. const String& cppCode) {
  164. if (type.isFloat()) {
  165. this->write("%f");
  166. fFormatArgs.push_back(cppCode);
  167. } else if (type == *fContext.fInt_Type) {
  168. this->write("%d");
  169. fFormatArgs.push_back(cppCode);
  170. } else if (type == *fContext.fBool_Type) {
  171. this->write("%s");
  172. fFormatArgs.push_back("(" + cppCode + " ? \"true\" : \"false\")");
  173. } else if (type == *fContext.fFloat2_Type || type == *fContext.fHalf2_Type) {
  174. this->write(type.name() + "(%f, %f)");
  175. fFormatArgs.push_back(cppCode + ".fX");
  176. fFormatArgs.push_back(cppCode + ".fY");
  177. } else if (type == *fContext.fFloat4_Type || type == *fContext.fHalf4_Type) {
  178. this->write(type.name() + "(%f, %f, %f, %f)");
  179. switch (layout.fCType) {
  180. case Layout::CType::kSkPMColor:
  181. fFormatArgs.push_back("SkGetPackedR32(" + cppCode + ") / 255.0");
  182. fFormatArgs.push_back("SkGetPackedG32(" + cppCode + ") / 255.0");
  183. fFormatArgs.push_back("SkGetPackedB32(" + cppCode + ") / 255.0");
  184. fFormatArgs.push_back("SkGetPackedA32(" + cppCode + ") / 255.0");
  185. break;
  186. case Layout::CType::kSkPMColor4f:
  187. fFormatArgs.push_back(cppCode + ".fR");
  188. fFormatArgs.push_back(cppCode + ".fG");
  189. fFormatArgs.push_back(cppCode + ".fB");
  190. fFormatArgs.push_back(cppCode + ".fA");
  191. break;
  192. case Layout::CType::kSkVector4:
  193. fFormatArgs.push_back(cppCode + ".fData[0]");
  194. fFormatArgs.push_back(cppCode + ".fData[1]");
  195. fFormatArgs.push_back(cppCode + ".fData[2]");
  196. fFormatArgs.push_back(cppCode + ".fData[3]");
  197. break;
  198. case Layout::CType::kSkRect: // fall through
  199. case Layout::CType::kDefault:
  200. fFormatArgs.push_back(cppCode + ".left()");
  201. fFormatArgs.push_back(cppCode + ".top()");
  202. fFormatArgs.push_back(cppCode + ".right()");
  203. fFormatArgs.push_back(cppCode + ".bottom()");
  204. break;
  205. default:
  206. SkASSERT(false);
  207. }
  208. } else if (type.kind() == Type::kEnum_Kind) {
  209. this->write("%d");
  210. fFormatArgs.push_back("(int) " + cppCode);
  211. } else if (type == *fContext.fInt4_Type ||
  212. type == *fContext.fShort4_Type ||
  213. type == *fContext.fByte4_Type) {
  214. this->write(type.name() + "(%d, %d, %d, %d)");
  215. fFormatArgs.push_back(cppCode + ".left()");
  216. fFormatArgs.push_back(cppCode + ".top()");
  217. fFormatArgs.push_back(cppCode + ".right()");
  218. fFormatArgs.push_back(cppCode + ".bottom()");
  219. } else {
  220. printf("unsupported runtime value type '%s'\n", String(type.fName).c_str());
  221. SkASSERT(false);
  222. }
  223. }
  224. void CPPCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
  225. if (is_private(var)) {
  226. this->writeRuntimeValue(var.fType, var.fModifiers.fLayout, var.fName);
  227. } else {
  228. this->writeExpression(value, kTopLevel_Precedence);
  229. }
  230. }
  231. String CPPCodeGenerator::getSamplerHandle(const Variable& var) {
  232. int samplerCount = 0;
  233. for (const auto param : fSectionAndParameterHelper.getParameters()) {
  234. if (&var == param) {
  235. return "args.fTexSamplers[" + to_string(samplerCount) + "]";
  236. }
  237. if (param->fType.kind() == Type::kSampler_Kind) {
  238. ++samplerCount;
  239. }
  240. }
  241. ABORT("should have found sampler in parameters\n");
  242. }
  243. void CPPCodeGenerator::writeIntLiteral(const IntLiteral& i) {
  244. this->write(to_string((int32_t) i.fValue));
  245. }
  246. void CPPCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
  247. if (fCPPMode) {
  248. SkASSERT(swizzle.fComponents.size() == 1); // no support for multiple swizzle components yet
  249. this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
  250. switch (swizzle.fComponents[0]) {
  251. case 0: this->write(".left()"); break;
  252. case 1: this->write(".top()"); break;
  253. case 2: this->write(".right()"); break;
  254. case 3: this->write(".bottom()"); break;
  255. }
  256. } else {
  257. INHERITED::writeSwizzle(swizzle);
  258. }
  259. }
  260. void CPPCodeGenerator::writeVariableReference(const VariableReference& ref) {
  261. if (fCPPMode) {
  262. this->write(ref.fVariable.fName);
  263. return;
  264. }
  265. switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
  266. case SK_INCOLOR_BUILTIN:
  267. this->write("%s");
  268. // EmitArgs.fInputColor is automatically set to half4(1) if
  269. // no input was specified
  270. fFormatArgs.push_back(String("args.fInputColor"));
  271. break;
  272. case SK_OUTCOLOR_BUILTIN:
  273. this->write("%s");
  274. fFormatArgs.push_back(String("args.fOutputColor"));
  275. break;
  276. case SK_WIDTH_BUILTIN:
  277. this->write("sk_Width");
  278. break;
  279. case SK_HEIGHT_BUILTIN:
  280. this->write("sk_Height");
  281. break;
  282. default:
  283. if (ref.fVariable.fType.kind() == Type::kSampler_Kind) {
  284. this->write("%s");
  285. fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerVariable(" +
  286. this->getSamplerHandle(ref.fVariable) + ")");
  287. return;
  288. }
  289. if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag) {
  290. this->write("%s");
  291. String name = ref.fVariable.fName;
  292. String var = String::printf("args.fUniformHandler->getUniformCStr(%sVar)",
  293. HCodeGenerator::FieldName(name.c_str()).c_str());
  294. String code;
  295. if (ref.fVariable.fModifiers.fLayout.fWhen.fLength) {
  296. code = String::printf("%sVar.isValid() ? %s : \"%s\"",
  297. HCodeGenerator::FieldName(name.c_str()).c_str(),
  298. var.c_str(),
  299. default_value(ref.fVariable.fType).c_str());
  300. } else {
  301. code = var;
  302. }
  303. fFormatArgs.push_back(code);
  304. } else if (SectionAndParameterHelper::IsParameter(ref.fVariable)) {
  305. String name(ref.fVariable.fName);
  306. this->writeRuntimeValue(ref.fVariable.fType, ref.fVariable.fModifiers.fLayout,
  307. String::printf("_outer.%s", name.c_str()).c_str());
  308. } else {
  309. this->write(ref.fVariable.fName);
  310. }
  311. }
  312. }
  313. void CPPCodeGenerator::writeIfStatement(const IfStatement& s) {
  314. if (s.fIsStatic) {
  315. this->write("@");
  316. }
  317. INHERITED::writeIfStatement(s);
  318. }
  319. void CPPCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
  320. if (fInMain) {
  321. fErrors.error(s.fOffset, "fragmentProcessor main() may not contain return statements");
  322. }
  323. INHERITED::writeReturnStatement(s);
  324. }
  325. void CPPCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
  326. if (s.fIsStatic) {
  327. this->write("@");
  328. }
  329. INHERITED::writeSwitchStatement(s);
  330. }
  331. void CPPCodeGenerator::writeFieldAccess(const FieldAccess& access) {
  332. if (access.fBase->fType.name() == "fragmentProcessor") {
  333. // Special field access on fragment processors are converted into function calls on
  334. // GrFragmentProcessor's getters.
  335. if (access.fBase->fKind != Expression::kVariableReference_Kind) {
  336. fErrors.error(access.fBase->fOffset, "fragmentProcessor must be a reference\n");
  337. return;
  338. }
  339. const Type::Field& field = fContext.fFragmentProcessor_Type->fields()[access.fFieldIndex];
  340. const Variable& var = ((const VariableReference&) *access.fBase).fVariable;
  341. String cppAccess = String::printf("_outer.childProcessor(_outer.%s_index).%s()",
  342. String(var.fName).c_str(),
  343. String(field.fName).c_str());
  344. if (fCPPMode) {
  345. this->write(cppAccess.c_str());
  346. } else {
  347. writeRuntimeValue(*field.fType, Layout(), cppAccess);
  348. }
  349. return;
  350. }
  351. INHERITED::writeFieldAccess(access);
  352. }
  353. int CPPCodeGenerator::getChildFPIndex(const Variable& var) const {
  354. int index = 0;
  355. bool found = false;
  356. for (const auto& p : fProgram) {
  357. if (ProgramElement::kVar_Kind == p.fKind) {
  358. const VarDeclarations& decls = (const VarDeclarations&) p;
  359. for (const auto& raw : decls.fVars) {
  360. const VarDeclaration& decl = (VarDeclaration&) *raw;
  361. if (decl.fVar == &var) {
  362. found = true;
  363. } else if (decl.fVar->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
  364. ++index;
  365. }
  366. }
  367. }
  368. if (found) {
  369. break;
  370. }
  371. }
  372. SkASSERT(found);
  373. return index;
  374. }
  375. void CPPCodeGenerator::writeFunctionCall(const FunctionCall& c) {
  376. if (c.fFunction.fBuiltin && c.fFunction.fName == "process") {
  377. // Sanity checks that are detected by function definition in sksl_fp.inc
  378. SkASSERT(c.fArguments.size() == 1 || c.fArguments.size() == 2);
  379. SkASSERT("fragmentProcessor" == c.fArguments[0]->fType.name() ||
  380. "fragmentProcessor?" == c.fArguments[0]->fType.name());
  381. // Actually fail during compilation if arguments with valid types are
  382. // provided that are not variable references, since process() is a
  383. // special function that impacts code emission.
  384. if (c.fArguments[0]->fKind != Expression::kVariableReference_Kind) {
  385. fErrors.error(c.fArguments[0]->fOffset,
  386. "process()'s fragmentProcessor argument must be a variable reference\n");
  387. return;
  388. }
  389. if (c.fArguments.size() > 1) {
  390. // Second argument must also be a half4 expression
  391. SkASSERT("half4" == c.fArguments[1]->fType.name());
  392. }
  393. const Variable& child = ((const VariableReference&) *c.fArguments[0]).fVariable;
  394. int index = getChildFPIndex(child);
  395. // Start a new extra emit code section so that the emitted child processor can depend on
  396. // sksl variables defined in earlier sksl code.
  397. this->newExtraEmitCodeBlock();
  398. // Set to the empty string when no input color parameter should be emitted, which means this
  399. // must be properly formatted with a prefixed comma when the parameter should be inserted
  400. // into the emitChild() parameter list.
  401. String inputArg;
  402. if (c.fArguments.size() > 1) {
  403. SkASSERT(c.fArguments.size() == 2);
  404. // Use the emitChild() variant that accepts an input color, so convert the 2nd
  405. // argument's expression into C++ code that produces sksl stored in an SkString.
  406. String inputName = "_input" + to_string(index);
  407. addExtraEmitCodeLine(convertSKSLExpressionToCPP(*c.fArguments[1], inputName));
  408. // emitChild() needs a char*
  409. inputArg = ", " + inputName + ".c_str()";
  410. }
  411. // Write the output handling after the possible input handling
  412. String childName = "_child" + to_string(index);
  413. addExtraEmitCodeLine("SkString " + childName + "(\"" + childName + "\");");
  414. if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
  415. addExtraEmitCodeLine("if (_outer." + String(child.fName) + "_index >= 0) {\n ");
  416. }
  417. addExtraEmitCodeLine("this->emitChild(_outer." + String(child.fName) + "_index" +
  418. inputArg + ", &" + childName + ", args);");
  419. if (c.fArguments[0]->fType.kind() == Type::kNullable_Kind) {
  420. // Null FPs are not emitted, but their output can still be referenced in dependent
  421. // expressions - thus we always declare the variable.
  422. // Note: this is essentially dead code required to satisfy the compiler, because
  423. // 'process' function calls should always be guarded at a higher level, in the .fp
  424. // source.
  425. addExtraEmitCodeLine(
  426. "} else {"
  427. " fragBuilder->codeAppendf(\"half4 %s;\", " + childName + ".c_str());"
  428. "}");
  429. }
  430. this->write("%s");
  431. fFormatArgs.push_back(childName + ".c_str()");
  432. return;
  433. }
  434. INHERITED::writeFunctionCall(c);
  435. if (c.fFunction.fBuiltin && c.fFunction.fName == "texture") {
  436. this->write(".%s");
  437. SkASSERT(c.fArguments.size() >= 1);
  438. SkASSERT(c.fArguments[0]->fKind == Expression::kVariableReference_Kind);
  439. String sampler = this->getSamplerHandle(((VariableReference&) *c.fArguments[0]).fVariable);
  440. fFormatArgs.push_back("fragBuilder->getProgramBuilder()->samplerSwizzle(" + sampler +
  441. ").c_str()");
  442. }
  443. }
  444. void CPPCodeGenerator::writeFunction(const FunctionDefinition& f) {
  445. if (f.fDeclaration.fName == "main") {
  446. fFunctionHeader = "";
  447. OutputStream* oldOut = fOut;
  448. StringStream buffer;
  449. fOut = &buffer;
  450. fInMain = true;
  451. for (const auto& s : ((Block&) *f.fBody).fStatements) {
  452. this->writeStatement(*s);
  453. this->writeLine();
  454. }
  455. fInMain = false;
  456. fOut = oldOut;
  457. this->write(fFunctionHeader);
  458. this->write(buffer.str());
  459. } else {
  460. INHERITED::writeFunction(f);
  461. }
  462. }
  463. void CPPCodeGenerator::writeSetting(const Setting& s) {
  464. static constexpr const char* kPrefix = "sk_Args.";
  465. if (!strncmp(s.fName.c_str(), kPrefix, strlen(kPrefix))) {
  466. const char* name = s.fName.c_str() + strlen(kPrefix);
  467. this->writeRuntimeValue(s.fType, Layout(), HCodeGenerator::FieldName(name).c_str());
  468. } else {
  469. this->write(s.fName.c_str());
  470. }
  471. }
  472. bool CPPCodeGenerator::writeSection(const char* name, const char* prefix) {
  473. const Section* s = fSectionAndParameterHelper.getSection(name);
  474. if (s) {
  475. this->writef("%s%s", prefix, s->fText.c_str());
  476. return true;
  477. }
  478. return false;
  479. }
  480. void CPPCodeGenerator::writeProgramElement(const ProgramElement& p) {
  481. if (p.fKind == ProgramElement::kSection_Kind) {
  482. return;
  483. }
  484. if (p.fKind == ProgramElement::kVar_Kind) {
  485. const VarDeclarations& decls = (const VarDeclarations&) p;
  486. if (!decls.fVars.size()) {
  487. return;
  488. }
  489. const Variable& var = *((VarDeclaration&) *decls.fVars[0]).fVar;
  490. if (var.fModifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kUniform_Flag) ||
  491. -1 != var.fModifiers.fLayout.fBuiltin) {
  492. return;
  493. }
  494. }
  495. INHERITED::writeProgramElement(p);
  496. }
  497. void CPPCodeGenerator::addUniform(const Variable& var) {
  498. if (!needs_uniform_var(var)) {
  499. return;
  500. }
  501. const char* type;
  502. if (var.fType == *fContext.fFloat_Type) {
  503. type = "kFloat_GrSLType";
  504. } else if (var.fType == *fContext.fHalf_Type) {
  505. type = "kHalf_GrSLType";
  506. } else if (var.fType == *fContext.fFloat2_Type) {
  507. type = "kFloat2_GrSLType";
  508. } else if (var.fType == *fContext.fHalf2_Type) {
  509. type = "kHalf2_GrSLType";
  510. } else if (var.fType == *fContext.fFloat4_Type) {
  511. type = "kFloat4_GrSLType";
  512. } else if (var.fType == *fContext.fHalf4_Type) {
  513. type = "kHalf4_GrSLType";
  514. } else if (var.fType == *fContext.fFloat4x4_Type) {
  515. type = "kFloat4x4_GrSLType";
  516. } else if (var.fType == *fContext.fHalf4x4_Type) {
  517. type = "kHalf4x4_GrSLType";
  518. } else {
  519. ABORT("unsupported uniform type: %s %s;\n", String(var.fType.fName).c_str(),
  520. String(var.fName).c_str());
  521. }
  522. if (var.fModifiers.fLayout.fWhen.fLength) {
  523. this->writef(" if (%s) {\n ", String(var.fModifiers.fLayout.fWhen).c_str());
  524. }
  525. String name(var.fName);
  526. this->writef(" %sVar = args.fUniformHandler->addUniform(kFragment_GrShaderFlag, %s, "
  527. "\"%s\");\n", HCodeGenerator::FieldName(name.c_str()).c_str(), type,
  528. name.c_str());
  529. if (var.fModifiers.fLayout.fWhen.fLength) {
  530. this->write(" }\n");
  531. }
  532. }
  533. void CPPCodeGenerator::writeInputVars() {
  534. }
  535. void CPPCodeGenerator::writePrivateVars() {
  536. for (const auto& p : fProgram) {
  537. if (ProgramElement::kVar_Kind == p.fKind) {
  538. const VarDeclarations& decls = (const VarDeclarations&) p;
  539. for (const auto& raw : decls.fVars) {
  540. VarDeclaration& decl = (VarDeclaration&) *raw;
  541. if (is_private(*decl.fVar)) {
  542. if (decl.fVar->fType == *fContext.fFragmentProcessor_Type) {
  543. fErrors.error(decl.fOffset,
  544. "fragmentProcessor variables must be declared 'in'");
  545. return;
  546. }
  547. this->writef("%s %s = %s;\n",
  548. HCodeGenerator::FieldType(fContext, decl.fVar->fType,
  549. decl.fVar->fModifiers.fLayout).c_str(),
  550. String(decl.fVar->fName).c_str(),
  551. default_value(*decl.fVar).c_str());
  552. } else if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
  553. // An auto-tracked uniform in variable, so add a field to hold onto the prior
  554. // state. Note that tracked variables must be uniform in's and that is validated
  555. // before writePrivateVars() is called.
  556. const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *decl.fVar);
  557. SkASSERT(mapper && mapper->supportsTracking());
  558. String name = HCodeGenerator::FieldName(String(decl.fVar->fName).c_str());
  559. // The member statement is different if the mapper reports a default value
  560. if (mapper->defaultValue().size() > 0) {
  561. this->writef("%s %sPrev = %s;\n",
  562. Layout::CTypeToStr(mapper->ctype()), name.c_str(),
  563. mapper->defaultValue().c_str());
  564. } else {
  565. this->writef("%s %sPrev;\n",
  566. Layout::CTypeToStr(mapper->ctype()), name.c_str());
  567. }
  568. }
  569. }
  570. }
  571. }
  572. }
  573. void CPPCodeGenerator::writePrivateVarValues() {
  574. for (const auto& p : fProgram) {
  575. if (ProgramElement::kVar_Kind == p.fKind) {
  576. const VarDeclarations& decls = (const VarDeclarations&) p;
  577. for (const auto& raw : decls.fVars) {
  578. VarDeclaration& decl = (VarDeclaration&) *raw;
  579. if (is_private(*decl.fVar) && decl.fValue) {
  580. this->writef("%s = ", String(decl.fVar->fName).c_str());
  581. fCPPMode = true;
  582. this->writeExpression(*decl.fValue, kAssignment_Precedence);
  583. fCPPMode = false;
  584. this->write(";\n");
  585. }
  586. }
  587. }
  588. }
  589. }
  590. static bool is_accessible(const Variable& var) {
  591. const Type& type = var.fType.nonnullable();
  592. return Type::kSampler_Kind != type.kind() &&
  593. Type::kOther_Kind != type.kind();
  594. }
  595. void CPPCodeGenerator::newExtraEmitCodeBlock() {
  596. // This should only be called when emitting SKSL for emitCode(), which can be detected if the
  597. // cpp buffer is not null, and the cpp buffer is not the current output.
  598. SkASSERT(fCPPBuffer && fCPPBuffer != fOut);
  599. // Start a new block as an empty string
  600. fExtraEmitCodeBlocks.push_back("");
  601. // Mark its location in the output buffer, uses ${\d} for the token since ${} will not occur in
  602. // valid sksl and makes detection trivial.
  603. this->writef("${%zu}", fExtraEmitCodeBlocks.size() - 1);
  604. }
  605. void CPPCodeGenerator::addExtraEmitCodeLine(const String& toAppend) {
  606. SkASSERT(fExtraEmitCodeBlocks.size() > 0);
  607. String& currentBlock = fExtraEmitCodeBlocks[fExtraEmitCodeBlocks.size() - 1];
  608. // Automatically add indentation and newline
  609. currentBlock += " " + toAppend + "\n";
  610. }
  611. void CPPCodeGenerator::flushEmittedCode() {
  612. if (fCPPBuffer == nullptr) {
  613. // Not actually within writeEmitCode() so nothing to flush
  614. return;
  615. }
  616. StringStream* skslBuffer = static_cast<StringStream*>(fOut);
  617. String sksl = skslBuffer->str();
  618. // Empty the accumulation buffer since its current contents are consumed.
  619. skslBuffer->reset();
  620. // Switch to the cpp buffer
  621. fOut = fCPPBuffer;
  622. // Iterate through the sksl, keeping track of where the last statement ended (e.g. the latest
  623. // encountered ';', '{', or '}'). If an extra emit code block token is encountered then the
  624. // code from 0 to last statement end is sent to writeCodeAppend, the extra code block is
  625. // appended to the cpp buffer, and then the sksl string is trimmed to start where the last
  626. // statement left off (minus the encountered token).
  627. size_t i = 0;
  628. int flushPoint = -1;
  629. int tokenStart = -1;
  630. while (i < sksl.size()) {
  631. if (tokenStart >= 0) {
  632. // Looking for the end of the token
  633. if (sksl[i] == '}') {
  634. // Must append the sksl from 0 to flushPoint (inclusive) then the extra code
  635. // accumulated in the block with index parsed from chars [tokenStart+2, i-1]
  636. String toFlush = String(sksl.c_str(), flushPoint + 1);
  637. // writeCodeAppend automatically removes the format args that it consumed, so
  638. // fFormatArgs will be in a valid state for any future sksl
  639. this->writeCodeAppend(toFlush);
  640. int codeBlock = stoi(String(sksl.c_str() + tokenStart + 2, i - tokenStart - 2));
  641. SkASSERT(codeBlock < (int) fExtraEmitCodeBlocks.size());
  642. if (fExtraEmitCodeBlocks[codeBlock].size() > 0) {
  643. this->write(fExtraEmitCodeBlocks[codeBlock].c_str());
  644. }
  645. // Now reset the sksl buffer to start after the flush point, but remove the token.
  646. String compacted = String(sksl.c_str() + flushPoint + 1,
  647. tokenStart - flushPoint - 1);
  648. if (i < sksl.size() - 1) {
  649. compacted += String(sksl.c_str() + i + 1, sksl.size() - i - 1);
  650. }
  651. sksl = compacted;
  652. // And reset iteration
  653. i = -1;
  654. flushPoint = -1;
  655. tokenStart = -1;
  656. }
  657. } else {
  658. // Looking for the start of extra emit block tokens, and tracking when statements end
  659. if (sksl[i] == ';' || sksl[i] == '{' || sksl[i] == '}') {
  660. flushPoint = i;
  661. } else if (i < sksl.size() - 1 && sksl[i] == '$' && sksl[i + 1] == '{') {
  662. // found an extra emit code block token
  663. tokenStart = i++;
  664. }
  665. }
  666. i++;
  667. }
  668. // Once we've gone through the sksl string to this point, there are no remaining extra emit
  669. // code blocks to interleave, so append the remainder as usual.
  670. this->writeCodeAppend(sksl);
  671. // After appending, switch back to the emptied sksl buffer and reset the extra code blocks
  672. fOut = skslBuffer;
  673. fExtraEmitCodeBlocks.clear();
  674. }
  675. void CPPCodeGenerator::writeCodeAppend(const String& code) {
  676. // codeAppendf can only handle appending 1024 bytes at a time, so we need to break the string
  677. // into chunks. Unfortunately we can't tell exactly how long the string is going to end up,
  678. // because printf escape sequences get replaced by strings of unknown length, but keeping the
  679. // format string below 512 bytes is probably safe.
  680. static constexpr size_t maxChunkSize = 512;
  681. size_t start = 0;
  682. size_t index = 0;
  683. size_t argStart = 0;
  684. size_t argCount;
  685. while (index < code.size()) {
  686. argCount = 0;
  687. this->write(" fragBuilder->codeAppendf(\"");
  688. while (index < code.size() && index < start + maxChunkSize) {
  689. if ('%' == code[index]) {
  690. if (index == start + maxChunkSize - 1 || index == code.size() - 1) {
  691. break;
  692. }
  693. if (code[index + 1] != '%') {
  694. ++argCount;
  695. }
  696. } else if ('\\' == code[index] && index == start + maxChunkSize - 1) {
  697. // avoid splitting an escape sequence that happens to fall across a chunk boundary
  698. break;
  699. }
  700. ++index;
  701. }
  702. fOut->write(code.c_str() + start, index - start);
  703. this->write("\"");
  704. for (size_t i = argStart; i < argStart + argCount; ++i) {
  705. this->writef(", %s", fFormatArgs[i].c_str());
  706. }
  707. this->write(");\n");
  708. argStart += argCount;
  709. start = index;
  710. }
  711. // argStart is equal to the number of fFormatArgs that were consumed
  712. // so they should be removed from the list
  713. if (argStart > 0) {
  714. fFormatArgs.erase(fFormatArgs.begin(), fFormatArgs.begin() + argStart);
  715. }
  716. }
  717. String CPPCodeGenerator::convertSKSLExpressionToCPP(const Expression& e,
  718. const String& cppVar) {
  719. // To do this conversion, we temporarily switch the sksl output stream
  720. // to an empty stringstream and reset the format args to empty.
  721. OutputStream* oldSKSL = fOut;
  722. StringStream exprBuffer;
  723. fOut = &exprBuffer;
  724. std::vector<String> oldArgs(fFormatArgs);
  725. fFormatArgs.clear();
  726. // Convert the argument expression into a format string and args
  727. this->writeExpression(e, Precedence::kTopLevel_Precedence);
  728. std::vector<String> newArgs(fFormatArgs);
  729. String expr = exprBuffer.str();
  730. // After generating, restore the original output stream and format args
  731. fFormatArgs = oldArgs;
  732. fOut = oldSKSL;
  733. // The sksl written to exprBuffer is not processed by flushEmittedCode(), so any extra emit code
  734. // block tokens won't get handled. So we need to strip them from the expression and stick them
  735. // to the end of the original sksl stream.
  736. String exprFormat = "";
  737. int tokenStart = -1;
  738. for (size_t i = 0; i < expr.size(); i++) {
  739. if (tokenStart >= 0) {
  740. if (expr[i] == '}') {
  741. // End of the token, so append the token to fOut
  742. fOut->write(expr.c_str() + tokenStart, i - tokenStart + 1);
  743. tokenStart = -1;
  744. }
  745. } else {
  746. if (i < expr.size() - 1 && expr[i] == '$' && expr[i + 1] == '{') {
  747. tokenStart = i++;
  748. } else {
  749. exprFormat += expr[i];
  750. }
  751. }
  752. }
  753. // Now build the final C++ code snippet from the format string and args
  754. String cppExpr;
  755. if (newArgs.size() == 0) {
  756. // This was a static expression, so we can simplify the input
  757. // color declaration in the emitted code to just a static string
  758. cppExpr = "SkString " + cppVar + "(\"" + exprFormat + "\");";
  759. } else {
  760. // String formatting must occur dynamically, so have the C++ declaration
  761. // use SkStringPrintf with the format args that were accumulated
  762. // when the expression was written.
  763. cppExpr = "SkString " + cppVar + " = SkStringPrintf(\"" + exprFormat + "\"";
  764. for (size_t i = 0; i < newArgs.size(); i++) {
  765. cppExpr += ", " + newArgs[i];
  766. }
  767. cppExpr += ");";
  768. }
  769. return cppExpr;
  770. }
  771. bool CPPCodeGenerator::writeEmitCode(std::vector<const Variable*>& uniforms) {
  772. this->write(" void emitCode(EmitArgs& args) override {\n"
  773. " GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;\n");
  774. this->writef(" const %s& _outer = args.fFp.cast<%s>();\n"
  775. " (void) _outer;\n",
  776. fFullName.c_str(), fFullName.c_str());
  777. for (const auto& p : fProgram) {
  778. if (ProgramElement::kVar_Kind == p.fKind) {
  779. const VarDeclarations& decls = (const VarDeclarations&) p;
  780. for (const auto& raw : decls.fVars) {
  781. VarDeclaration& decl = (VarDeclaration&) *raw;
  782. String nameString(decl.fVar->fName);
  783. const char* name = nameString.c_str();
  784. if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
  785. is_accessible(*decl.fVar)) {
  786. this->writef(" auto %s = _outer.%s;\n"
  787. " (void) %s;\n",
  788. name, name, name);
  789. }
  790. }
  791. }
  792. }
  793. this->writePrivateVarValues();
  794. for (const auto u : uniforms) {
  795. this->addUniform(*u);
  796. }
  797. this->writeSection(EMIT_CODE_SECTION);
  798. // Save original buffer as the CPP buffer for flushEmittedCode()
  799. fCPPBuffer = fOut;
  800. StringStream skslBuffer;
  801. fOut = &skslBuffer;
  802. this->newExtraEmitCodeBlock();
  803. bool result = INHERITED::generateCode();
  804. this->flushEmittedCode();
  805. // Then restore the original CPP buffer and close the function
  806. fOut = fCPPBuffer;
  807. fCPPBuffer = nullptr;
  808. this->write(" }\n");
  809. return result;
  810. }
  811. void CPPCodeGenerator::writeSetData(std::vector<const Variable*>& uniforms) {
  812. const char* fullName = fFullName.c_str();
  813. const Section* section = fSectionAndParameterHelper.getSection(SET_DATA_SECTION);
  814. const char* pdman = section ? section->fArgument.c_str() : "pdman";
  815. this->writef(" void onSetData(const GrGLSLProgramDataManager& %s, "
  816. "const GrFragmentProcessor& _proc) override {\n",
  817. pdman);
  818. bool wroteProcessor = false;
  819. for (const auto u : uniforms) {
  820. if (is_uniform_in(*u)) {
  821. if (!wroteProcessor) {
  822. this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName, fullName);
  823. wroteProcessor = true;
  824. this->writef(" {\n");
  825. }
  826. const UniformCTypeMapper* mapper = UniformCTypeMapper::Get(fContext, *u);
  827. SkASSERT(mapper);
  828. String nameString(u->fName);
  829. const char* name = nameString.c_str();
  830. // Switches for setData behavior in the generated code
  831. bool conditionalUniform = u->fModifiers.fLayout.fWhen != "";
  832. bool isTracked = u->fModifiers.fLayout.fFlags & Layout::kTracked_Flag;
  833. bool needsValueDeclaration = isTracked || !mapper->canInlineUniformValue();
  834. String uniformName = HCodeGenerator::FieldName(name) + "Var";
  835. String indent = " "; // 8 by default, 12 when nested for conditional uniforms
  836. if (conditionalUniform) {
  837. // Add a pre-check to make sure the uniform was emitted
  838. // before trying to send any data to the GPU
  839. this->writef(" if (%s.isValid()) {\n", uniformName.c_str());
  840. indent += " ";
  841. }
  842. String valueVar = "";
  843. if (needsValueDeclaration) {
  844. valueVar.appendf("%sValue", name);
  845. // Use AccessType since that will match the return type of _outer's public API.
  846. String valueType = HCodeGenerator::AccessType(fContext, u->fType,
  847. u->fModifiers.fLayout);
  848. this->writef("%s%s %s = _outer.%s;\n",
  849. indent.c_str(), valueType.c_str(), valueVar.c_str(), name);
  850. } else {
  851. // Not tracked and the mapper only needs to use the value once
  852. // so send it a safe expression instead of the variable name
  853. valueVar.appendf("(_outer.%s)", name);
  854. }
  855. if (isTracked) {
  856. SkASSERT(mapper->supportsTracking());
  857. String prevVar = HCodeGenerator::FieldName(name) + "Prev";
  858. this->writef("%sif (%s) {\n"
  859. "%s %s;\n"
  860. "%s %s;\n"
  861. "%s}\n", indent.c_str(),
  862. mapper->dirtyExpression(valueVar, prevVar).c_str(), indent.c_str(),
  863. mapper->saveState(valueVar, prevVar).c_str(), indent.c_str(),
  864. mapper->setUniform(pdman, uniformName, valueVar).c_str(), indent.c_str());
  865. } else {
  866. this->writef("%s%s;\n", indent.c_str(),
  867. mapper->setUniform(pdman, uniformName, valueVar).c_str());
  868. }
  869. if (conditionalUniform) {
  870. // Close the earlier precheck block
  871. this->writef(" }\n");
  872. }
  873. }
  874. }
  875. if (wroteProcessor) {
  876. this->writef(" }\n");
  877. }
  878. if (section) {
  879. int samplerIndex = 0;
  880. for (const auto& p : fProgram) {
  881. if (ProgramElement::kVar_Kind == p.fKind) {
  882. const VarDeclarations& decls = (const VarDeclarations&) p;
  883. for (const auto& raw : decls.fVars) {
  884. VarDeclaration& decl = (VarDeclaration&) *raw;
  885. String nameString(decl.fVar->fName);
  886. const char* name = nameString.c_str();
  887. if (decl.fVar->fType.kind() == Type::kSampler_Kind) {
  888. this->writef(" GrSurfaceProxy& %sProxy = "
  889. "*_outer.textureSampler(%d).proxy();\n",
  890. name, samplerIndex);
  891. this->writef(" GrTexture& %s = *%sProxy.peekTexture();\n",
  892. name, name);
  893. this->writef(" (void) %s;\n", name);
  894. ++samplerIndex;
  895. } else if (needs_uniform_var(*decl.fVar)) {
  896. this->writef(" UniformHandle& %s = %sVar;\n"
  897. " (void) %s;\n",
  898. name, HCodeGenerator::FieldName(name).c_str(), name);
  899. } else if (SectionAndParameterHelper::IsParameter(*decl.fVar) &&
  900. decl.fVar->fType != *fContext.fFragmentProcessor_Type) {
  901. if (!wroteProcessor) {
  902. this->writef(" const %s& _outer = _proc.cast<%s>();\n", fullName,
  903. fullName);
  904. wroteProcessor = true;
  905. }
  906. this->writef(" auto %s = _outer.%s;\n"
  907. " (void) %s;\n",
  908. name, name, name);
  909. }
  910. }
  911. }
  912. }
  913. this->writeSection(SET_DATA_SECTION);
  914. }
  915. this->write(" }\n");
  916. }
  917. void CPPCodeGenerator::writeOnTextureSampler() {
  918. bool foundSampler = false;
  919. for (const auto& param : fSectionAndParameterHelper.getParameters()) {
  920. if (param->fType.kind() == Type::kSampler_Kind) {
  921. if (!foundSampler) {
  922. this->writef(
  923. "const GrFragmentProcessor::TextureSampler& %s::onTextureSampler(int "
  924. "index) const {\n",
  925. fFullName.c_str());
  926. this->writef(" return IthTextureSampler(index, %s",
  927. HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
  928. foundSampler = true;
  929. } else {
  930. this->writef(", %s",
  931. HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
  932. }
  933. }
  934. }
  935. if (foundSampler) {
  936. this->write(");\n}\n");
  937. }
  938. }
  939. void CPPCodeGenerator::writeClone() {
  940. if (!this->writeSection(CLONE_SECTION)) {
  941. if (fSectionAndParameterHelper.getSection(FIELDS_SECTION)) {
  942. fErrors.error(0, "fragment processors with custom @fields must also have a custom"
  943. "@clone");
  944. }
  945. this->writef("%s::%s(const %s& src)\n"
  946. ": INHERITED(k%s_ClassID, src.optimizationFlags())", fFullName.c_str(),
  947. fFullName.c_str(), fFullName.c_str(), fFullName.c_str());
  948. const auto transforms = fSectionAndParameterHelper.getSections(COORD_TRANSFORM_SECTION);
  949. for (size_t i = 0; i < transforms.size(); ++i) {
  950. const Section& s = *transforms[i];
  951. String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
  952. this->writef("\n, %s(src.%s)", fieldName.c_str(), fieldName.c_str());
  953. }
  954. for (const auto& param : fSectionAndParameterHelper.getParameters()) {
  955. String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
  956. if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
  957. this->writef("\n, %s_index(src.%s_index)",
  958. fieldName.c_str(),
  959. fieldName.c_str());
  960. } else {
  961. this->writef("\n, %s(src.%s)",
  962. fieldName.c_str(),
  963. fieldName.c_str());
  964. }
  965. }
  966. this->writef(" {\n");
  967. int samplerCount = 0;
  968. for (const auto& param : fSectionAndParameterHelper.getParameters()) {
  969. if (param->fType.kind() == Type::kSampler_Kind) {
  970. ++samplerCount;
  971. } else if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
  972. String fieldName = HCodeGenerator::FieldName(String(param->fName).c_str());
  973. if (param->fType.kind() == Type::kNullable_Kind) {
  974. this->writef(" if (%s_index >= 0) {\n ", fieldName.c_str());
  975. }
  976. this->writef(" this->registerChildProcessor(src.childProcessor(%s_index)."
  977. "clone());\n", fieldName.c_str());
  978. if (param->fType.kind() == Type::kNullable_Kind) {
  979. this->writef(" }\n");
  980. }
  981. }
  982. }
  983. if (samplerCount) {
  984. this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
  985. }
  986. for (size_t i = 0; i < transforms.size(); ++i) {
  987. const Section& s = *transforms[i];
  988. String fieldName = HCodeGenerator::CoordTransformName(s.fArgument, i);
  989. this->writef(" this->addCoordTransform(&%s);\n", fieldName.c_str());
  990. }
  991. this->write("}\n");
  992. this->writef("std::unique_ptr<GrFragmentProcessor> %s::clone() const {\n",
  993. fFullName.c_str());
  994. this->writef(" return std::unique_ptr<GrFragmentProcessor>(new %s(*this));\n",
  995. fFullName.c_str());
  996. this->write("}\n");
  997. }
  998. }
  999. void CPPCodeGenerator::writeTest() {
  1000. const Section* test = fSectionAndParameterHelper.getSection(TEST_CODE_SECTION);
  1001. if (test) {
  1002. this->writef(
  1003. "GR_DEFINE_FRAGMENT_PROCESSOR_TEST(%s);\n"
  1004. "#if GR_TEST_UTILS\n"
  1005. "std::unique_ptr<GrFragmentProcessor> %s::TestCreate(GrProcessorTestData* %s) {\n",
  1006. fFullName.c_str(),
  1007. fFullName.c_str(),
  1008. test->fArgument.c_str());
  1009. this->writeSection(TEST_CODE_SECTION);
  1010. this->write("}\n"
  1011. "#endif\n");
  1012. }
  1013. }
  1014. void CPPCodeGenerator::writeGetKey() {
  1015. this->writef("void %s::onGetGLSLProcessorKey(const GrShaderCaps& caps, "
  1016. "GrProcessorKeyBuilder* b) const {\n",
  1017. fFullName.c_str());
  1018. for (const auto& p : fProgram) {
  1019. if (ProgramElement::kVar_Kind == p.fKind) {
  1020. const VarDeclarations& decls = (const VarDeclarations&) p;
  1021. for (const auto& raw : decls.fVars) {
  1022. const VarDeclaration& decl = (VarDeclaration&) *raw;
  1023. const Variable& var = *decl.fVar;
  1024. String nameString(var.fName);
  1025. const char* name = nameString.c_str();
  1026. if (var.fModifiers.fLayout.fKey != Layout::kNo_Key &&
  1027. (var.fModifiers.fFlags & Modifiers::kUniform_Flag)) {
  1028. fErrors.error(var.fOffset,
  1029. "layout(key) may not be specified on uniforms");
  1030. }
  1031. switch (var.fModifiers.fLayout.fKey) {
  1032. case Layout::kKey_Key:
  1033. if (is_private(var)) {
  1034. this->writef("%s %s =",
  1035. HCodeGenerator::FieldType(fContext, var.fType,
  1036. var.fModifiers.fLayout).c_str(),
  1037. String(var.fName).c_str());
  1038. if (decl.fValue) {
  1039. fCPPMode = true;
  1040. this->writeExpression(*decl.fValue, kAssignment_Precedence);
  1041. fCPPMode = false;
  1042. } else {
  1043. this->writef("%s", default_value(var).c_str());
  1044. }
  1045. this->write(";\n");
  1046. }
  1047. if (var.fModifiers.fLayout.fWhen.fLength) {
  1048. this->writef("if (%s) {", String(var.fModifiers.fLayout.fWhen).c_str());
  1049. }
  1050. if (var.fType == *fContext.fFloat4x4_Type) {
  1051. ABORT("no automatic key handling for float4x4\n");
  1052. } else if (var.fType == *fContext.fFloat2_Type) {
  1053. this->writef(" b->add32(%s.fX);\n",
  1054. HCodeGenerator::FieldName(name).c_str());
  1055. this->writef(" b->add32(%s.fY);\n",
  1056. HCodeGenerator::FieldName(name).c_str());
  1057. } else if (var.fType == *fContext.fFloat4_Type) {
  1058. this->writef(" b->add32(%s.x());\n",
  1059. HCodeGenerator::FieldName(name).c_str());
  1060. this->writef(" b->add32(%s.y());\n",
  1061. HCodeGenerator::FieldName(name).c_str());
  1062. this->writef(" b->add32(%s.width());\n",
  1063. HCodeGenerator::FieldName(name).c_str());
  1064. this->writef(" b->add32(%s.height());\n",
  1065. HCodeGenerator::FieldName(name).c_str());
  1066. } else if (var.fType == *fContext.fHalf4_Type) {
  1067. this->writef(" uint16_t red = SkFloatToHalf(%s.fR);\n",
  1068. HCodeGenerator::FieldName(name).c_str());
  1069. this->writef(" uint16_t green = SkFloatToHalf(%s.fG);\n",
  1070. HCodeGenerator::FieldName(name).c_str());
  1071. this->writef(" uint16_t blue = SkFloatToHalf(%s.fB);\n",
  1072. HCodeGenerator::FieldName(name).c_str());
  1073. this->writef(" uint16_t alpha = SkFloatToHalf(%s.fA);\n",
  1074. HCodeGenerator::FieldName(name).c_str());
  1075. this->write(" b->add32(((uint32_t)red << 16) | green);\n");
  1076. this->write(" b->add32(((uint32_t)blue << 16) | alpha);\n");
  1077. } else {
  1078. this->writef(" b->add32((int32_t) %s);\n",
  1079. HCodeGenerator::FieldName(name).c_str());
  1080. }
  1081. if (var.fModifiers.fLayout.fWhen.fLength) {
  1082. this->write("}");
  1083. }
  1084. break;
  1085. case Layout::kIdentity_Key:
  1086. if (var.fType.kind() != Type::kMatrix_Kind) {
  1087. fErrors.error(var.fOffset,
  1088. "layout(key=identity) requires matrix type");
  1089. }
  1090. this->writef(" b->add32(%s.isIdentity() ? 1 : 0);\n",
  1091. HCodeGenerator::FieldName(name).c_str());
  1092. break;
  1093. case Layout::kNo_Key:
  1094. break;
  1095. }
  1096. }
  1097. }
  1098. }
  1099. this->write("}\n");
  1100. }
  1101. bool CPPCodeGenerator::generateCode() {
  1102. std::vector<const Variable*> uniforms;
  1103. for (const auto& p : fProgram) {
  1104. if (ProgramElement::kVar_Kind == p.fKind) {
  1105. const VarDeclarations& decls = (const VarDeclarations&) p;
  1106. for (const auto& raw : decls.fVars) {
  1107. VarDeclaration& decl = (VarDeclaration&) *raw;
  1108. if ((decl.fVar->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
  1109. decl.fVar->fType.kind() != Type::kSampler_Kind) {
  1110. uniforms.push_back(decl.fVar);
  1111. }
  1112. if (is_uniform_in(*decl.fVar)) {
  1113. // Validate the "uniform in" declarations to make sure they are fully supported,
  1114. // instead of generating surprising C++
  1115. const UniformCTypeMapper* mapper =
  1116. UniformCTypeMapper::Get(fContext, *decl.fVar);
  1117. if (mapper == nullptr) {
  1118. fErrors.error(decl.fOffset, String(decl.fVar->fName)
  1119. + "'s type is not supported for use as a 'uniform in'");
  1120. return false;
  1121. }
  1122. if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
  1123. if (!mapper->supportsTracking()) {
  1124. fErrors.error(decl.fOffset, String(decl.fVar->fName)
  1125. + "'s type does not support state tracking");
  1126. return false;
  1127. }
  1128. }
  1129. } else {
  1130. // If it's not a uniform_in, it's an error to be tracked
  1131. if (decl.fVar->fModifiers.fLayout.fFlags & Layout::kTracked_Flag) {
  1132. fErrors.error(decl.fOffset, "Non-'in uniforms' cannot be tracked");
  1133. return false;
  1134. }
  1135. }
  1136. }
  1137. }
  1138. }
  1139. const char* baseName = fName.c_str();
  1140. const char* fullName = fFullName.c_str();
  1141. this->writef("%s\n", HCodeGenerator::GetHeader(fProgram, fErrors).c_str());
  1142. this->writef(kFragmentProcessorHeader, fullName);
  1143. this->writef("#include \"%s.h\"\n\n", fullName);
  1144. this->writeSection(CPP_SECTION);
  1145. this->writef("#include \"include/gpu/GrTexture.h\"\n"
  1146. "#include \"src/gpu/glsl/GrGLSLFragmentProcessor.h\"\n"
  1147. "#include \"src/gpu/glsl/GrGLSLFragmentShaderBuilder.h\"\n"
  1148. "#include \"src/gpu/glsl/GrGLSLProgramBuilder.h\"\n"
  1149. "#include \"src/sksl/SkSLCPP.h\"\n"
  1150. "#include \"src/sksl/SkSLUtil.h\"\n"
  1151. "class GrGLSL%s : public GrGLSLFragmentProcessor {\n"
  1152. "public:\n"
  1153. " GrGLSL%s() {}\n",
  1154. baseName, baseName);
  1155. bool result = this->writeEmitCode(uniforms);
  1156. this->write("private:\n");
  1157. this->writeSetData(uniforms);
  1158. this->writePrivateVars();
  1159. for (const auto& u : uniforms) {
  1160. if (needs_uniform_var(*u) && !(u->fModifiers.fFlags & Modifiers::kIn_Flag)) {
  1161. this->writef(" UniformHandle %sVar;\n",
  1162. HCodeGenerator::FieldName(String(u->fName).c_str()).c_str());
  1163. }
  1164. }
  1165. for (const auto& param : fSectionAndParameterHelper.getParameters()) {
  1166. if (needs_uniform_var(*param)) {
  1167. this->writef(" UniformHandle %sVar;\n",
  1168. HCodeGenerator::FieldName(String(param->fName).c_str()).c_str());
  1169. }
  1170. }
  1171. this->writef("};\n"
  1172. "GrGLSLFragmentProcessor* %s::onCreateGLSLInstance() const {\n"
  1173. " return new GrGLSL%s();\n"
  1174. "}\n",
  1175. fullName, baseName);
  1176. this->writeGetKey();
  1177. this->writef("bool %s::onIsEqual(const GrFragmentProcessor& other) const {\n"
  1178. " const %s& that = other.cast<%s>();\n"
  1179. " (void) that;\n",
  1180. fullName, fullName, fullName);
  1181. for (const auto& param : fSectionAndParameterHelper.getParameters()) {
  1182. if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
  1183. continue;
  1184. }
  1185. String nameString(param->fName);
  1186. const char* name = nameString.c_str();
  1187. this->writef(" if (%s != that.%s) return false;\n",
  1188. HCodeGenerator::FieldName(name).c_str(),
  1189. HCodeGenerator::FieldName(name).c_str());
  1190. }
  1191. this->write(" return true;\n"
  1192. "}\n");
  1193. this->writeClone();
  1194. this->writeOnTextureSampler();
  1195. this->writeTest();
  1196. this->writeSection(CPP_END_SECTION);
  1197. result &= 0 == fErrors.errorCount();
  1198. return result;
  1199. }
  1200. } // namespace