SkPerlinNoiseShader.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  1. /*
  2. * Copyright 2013 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 "include/effects/SkPerlinNoiseShader.h"
  8. #include "include/core/SkColorFilter.h"
  9. #include "include/core/SkShader.h"
  10. #include "include/core/SkString.h"
  11. #include "include/core/SkUnPreMultiply.h"
  12. #include "src/core/SkArenaAlloc.h"
  13. #include "src/core/SkMakeUnique.h"
  14. #include "src/core/SkReadBuffer.h"
  15. #include "src/core/SkWriteBuffer.h"
  16. #if SK_SUPPORT_GPU
  17. #include "include/private/GrRecordingContext.h"
  18. #include "src/gpu/GrCoordTransform.h"
  19. #include "src/gpu/GrRecordingContextPriv.h"
  20. #include "src/gpu/SkGr.h"
  21. #include "src/gpu/effects/generated/GrConstColorProcessor.h"
  22. #include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
  23. #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
  24. #include "src/gpu/glsl/GrGLSLProgramDataManager.h"
  25. #include "src/gpu/glsl/GrGLSLUniformHandler.h"
  26. #endif
  27. static const int kBlockSize = 256;
  28. static const int kBlockMask = kBlockSize - 1;
  29. static const int kPerlinNoise = 4096;
  30. static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
  31. static uint8_t improved_noise_permutations[] = {
  32. 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103,
  33. 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26,
  34. 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174,
  35. 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231,
  36. 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143,
  37. 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196,
  38. 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124,
  39. 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17,
  40. 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101,
  41. 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185,
  42. 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81,
  43. 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176,
  44. 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243,
  45. 141, 128, 195, 78, 66, 215, 61, 156, 180,
  46. 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103,
  47. 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26,
  48. 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174,
  49. 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231,
  50. 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143,
  51. 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196,
  52. 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124,
  53. 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17,
  54. 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101,
  55. 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185,
  56. 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81,
  57. 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176,
  58. 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243,
  59. 141, 128, 195, 78, 66, 215, 61, 156, 180
  60. };
  61. class SkPerlinNoiseShaderImpl : public SkShaderBase {
  62. public:
  63. struct StitchData {
  64. StitchData()
  65. : fWidth(0)
  66. , fWrapX(0)
  67. , fHeight(0)
  68. , fWrapY(0)
  69. {}
  70. StitchData(SkScalar w, SkScalar h)
  71. : fWidth(SkTMin(SkScalarRoundToInt(w), SK_MaxS32 - kPerlinNoise))
  72. , fWrapX(kPerlinNoise + fWidth)
  73. , fHeight(SkTMin(SkScalarRoundToInt(h), SK_MaxS32 - kPerlinNoise))
  74. , fWrapY(kPerlinNoise + fHeight) {}
  75. bool operator==(const StitchData& other) const {
  76. return fWidth == other.fWidth &&
  77. fWrapX == other.fWrapX &&
  78. fHeight == other.fHeight &&
  79. fWrapY == other.fWrapY;
  80. }
  81. int fWidth; // How much to subtract to wrap for stitching.
  82. int fWrapX; // Minimum value to wrap.
  83. int fHeight;
  84. int fWrapY;
  85. };
  86. struct PaintingData {
  87. PaintingData(const SkISize& tileSize, SkScalar seed,
  88. SkScalar baseFrequencyX, SkScalar baseFrequencyY,
  89. const SkMatrix& matrix)
  90. {
  91. SkVector tileVec;
  92. matrix.mapVector(SkIntToScalar(tileSize.fWidth), SkIntToScalar(tileSize.fHeight),
  93. &tileVec);
  94. SkSize scale;
  95. if (!matrix.decomposeScale(&scale, nullptr)) {
  96. scale.set(SK_ScalarNearlyZero, SK_ScalarNearlyZero);
  97. }
  98. fBaseFrequency.set(baseFrequencyX * SkScalarInvert(scale.width()),
  99. baseFrequencyY * SkScalarInvert(scale.height()));
  100. fTileSize.set(SkScalarRoundToInt(tileVec.fX), SkScalarRoundToInt(tileVec.fY));
  101. this->init(seed);
  102. if (!fTileSize.isEmpty()) {
  103. this->stitch();
  104. }
  105. #if SK_SUPPORT_GPU
  106. SkImageInfo info = SkImageInfo::MakeA8(kBlockSize, 1);
  107. SkPixmap permutationsPixmap(info, fLatticeSelector, info.minRowBytes());
  108. fPermutationsImage = SkImage::MakeFromRaster(permutationsPixmap, nullptr, nullptr);
  109. info = SkImageInfo::MakeN32Premul(kBlockSize, 4);
  110. SkPixmap noisePixmap(info, fNoise[0][0], info.minRowBytes());
  111. fNoiseImage = SkImage::MakeFromRaster(noisePixmap, nullptr, nullptr);
  112. info = SkImageInfo::MakeA8(256, 1);
  113. SkPixmap impPermutationsPixmap(info, improved_noise_permutations, info.minRowBytes());
  114. fImprovedPermutationsImage = SkImage::MakeFromRaster(impPermutationsPixmap, nullptr,
  115. nullptr);
  116. static uint8_t gradients[] = { 2, 2, 1, 0,
  117. 0, 2, 1, 0,
  118. 2, 0, 1, 0,
  119. 0, 0, 1, 0,
  120. 2, 1, 2, 0,
  121. 0, 1, 2, 0,
  122. 2, 1, 0, 0,
  123. 0, 1, 0, 0,
  124. 1, 2, 2, 0,
  125. 1, 0, 2, 0,
  126. 1, 2, 0, 0,
  127. 1, 0, 0, 0,
  128. 2, 2, 1, 0,
  129. 1, 0, 2, 0,
  130. 0, 2, 1, 0,
  131. 1, 0, 0, 0 };
  132. info = SkImageInfo::MakeN32Premul(16, 1);
  133. SkPixmap gradPixmap(info, gradients, info.minRowBytes());
  134. fGradientImage = SkImage::MakeFromRaster(gradPixmap, nullptr, nullptr);
  135. #endif
  136. }
  137. #if SK_SUPPORT_GPU
  138. PaintingData(const PaintingData& that)
  139. : fSeed(that.fSeed)
  140. , fTileSize(that.fTileSize)
  141. , fBaseFrequency(that.fBaseFrequency)
  142. , fStitchDataInit(that.fStitchDataInit)
  143. , fPermutationsImage(that.fPermutationsImage)
  144. , fNoiseImage(that.fNoiseImage)
  145. , fImprovedPermutationsImage(that.fImprovedPermutationsImage)
  146. , fGradientImage(that.fGradientImage) {
  147. memcpy(fLatticeSelector, that.fLatticeSelector, sizeof(fLatticeSelector));
  148. memcpy(fNoise, that.fNoise, sizeof(fNoise));
  149. memcpy(fGradient, that.fGradient, sizeof(fGradient));
  150. }
  151. #endif
  152. int fSeed;
  153. uint8_t fLatticeSelector[kBlockSize];
  154. uint16_t fNoise[4][kBlockSize][2];
  155. SkPoint fGradient[4][kBlockSize];
  156. SkISize fTileSize;
  157. SkVector fBaseFrequency;
  158. StitchData fStitchDataInit;
  159. private:
  160. #if SK_SUPPORT_GPU
  161. sk_sp<SkImage> fPermutationsImage;
  162. sk_sp<SkImage> fNoiseImage;
  163. sk_sp<SkImage> fImprovedPermutationsImage;
  164. sk_sp<SkImage> fGradientImage;
  165. #endif
  166. inline int random() {
  167. static const int gRandAmplitude = 16807; // 7**5; primitive root of m
  168. static const int gRandQ = 127773; // m / a
  169. static const int gRandR = 2836; // m % a
  170. int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
  171. if (result <= 0)
  172. result += kRandMaximum;
  173. fSeed = result;
  174. return result;
  175. }
  176. // Only called once. Could be part of the constructor.
  177. void init(SkScalar seed)
  178. {
  179. static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
  180. // According to the SVG spec, we must truncate (not round) the seed value.
  181. fSeed = SkScalarTruncToInt(seed);
  182. // The seed value clamp to the range [1, kRandMaximum - 1].
  183. if (fSeed <= 0) {
  184. fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
  185. }
  186. if (fSeed > kRandMaximum - 1) {
  187. fSeed = kRandMaximum - 1;
  188. }
  189. for (int channel = 0; channel < 4; ++channel) {
  190. for (int i = 0; i < kBlockSize; ++i) {
  191. fLatticeSelector[i] = i;
  192. fNoise[channel][i][0] = (random() % (2 * kBlockSize));
  193. fNoise[channel][i][1] = (random() % (2 * kBlockSize));
  194. }
  195. }
  196. for (int i = kBlockSize - 1; i > 0; --i) {
  197. int k = fLatticeSelector[i];
  198. int j = random() % kBlockSize;
  199. SkASSERT(j >= 0);
  200. SkASSERT(j < kBlockSize);
  201. fLatticeSelector[i] = fLatticeSelector[j];
  202. fLatticeSelector[j] = k;
  203. }
  204. // Perform the permutations now
  205. {
  206. // Copy noise data
  207. uint16_t noise[4][kBlockSize][2];
  208. for (int i = 0; i < kBlockSize; ++i) {
  209. for (int channel = 0; channel < 4; ++channel) {
  210. for (int j = 0; j < 2; ++j) {
  211. noise[channel][i][j] = fNoise[channel][i][j];
  212. }
  213. }
  214. }
  215. // Do permutations on noise data
  216. for (int i = 0; i < kBlockSize; ++i) {
  217. for (int channel = 0; channel < 4; ++channel) {
  218. for (int j = 0; j < 2; ++j) {
  219. fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
  220. }
  221. }
  222. }
  223. }
  224. // Half of the largest possible value for 16 bit unsigned int
  225. static const SkScalar gHalfMax16bits = 32767.5f;
  226. // Compute gradients from permutated noise data
  227. for (int channel = 0; channel < 4; ++channel) {
  228. for (int i = 0; i < kBlockSize; ++i) {
  229. fGradient[channel][i] = SkPoint::Make(
  230. (fNoise[channel][i][0] - kBlockSize) * gInvBlockSizef,
  231. (fNoise[channel][i][1] - kBlockSize) * gInvBlockSizef);
  232. fGradient[channel][i].normalize();
  233. // Put the normalized gradient back into the noise data
  234. fNoise[channel][i][0] = SkScalarRoundToInt(
  235. (fGradient[channel][i].fX + 1) * gHalfMax16bits);
  236. fNoise[channel][i][1] = SkScalarRoundToInt(
  237. (fGradient[channel][i].fY + 1) * gHalfMax16bits);
  238. }
  239. }
  240. }
  241. // Only called once. Could be part of the constructor.
  242. void stitch() {
  243. SkScalar tileWidth = SkIntToScalar(fTileSize.width());
  244. SkScalar tileHeight = SkIntToScalar(fTileSize.height());
  245. SkASSERT(tileWidth > 0 && tileHeight > 0);
  246. // When stitching tiled turbulence, the frequencies must be adjusted
  247. // so that the tile borders will be continuous.
  248. if (fBaseFrequency.fX) {
  249. SkScalar lowFrequencx =
  250. SkScalarFloorToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
  251. SkScalar highFrequencx =
  252. SkScalarCeilToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
  253. // BaseFrequency should be non-negative according to the standard.
  254. // lowFrequencx can be 0 if fBaseFrequency.fX is very small.
  255. if (sk_ieee_float_divide(fBaseFrequency.fX, lowFrequencx) < highFrequencx / fBaseFrequency.fX) {
  256. fBaseFrequency.fX = lowFrequencx;
  257. } else {
  258. fBaseFrequency.fX = highFrequencx;
  259. }
  260. }
  261. if (fBaseFrequency.fY) {
  262. SkScalar lowFrequency =
  263. SkScalarFloorToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
  264. SkScalar highFrequency =
  265. SkScalarCeilToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
  266. // lowFrequency can be 0 if fBaseFrequency.fY is very small.
  267. if (sk_ieee_float_divide(fBaseFrequency.fY, lowFrequency) < highFrequency / fBaseFrequency.fY) {
  268. fBaseFrequency.fY = lowFrequency;
  269. } else {
  270. fBaseFrequency.fY = highFrequency;
  271. }
  272. }
  273. // Set up TurbulenceInitial stitch values.
  274. fStitchDataInit = StitchData(tileWidth * fBaseFrequency.fX,
  275. tileHeight * fBaseFrequency.fY);
  276. }
  277. public:
  278. #if SK_SUPPORT_GPU
  279. const sk_sp<SkImage> getPermutationsImage() const { return fPermutationsImage; }
  280. const sk_sp<SkImage> getNoiseImage() const { return fNoiseImage; }
  281. const sk_sp<SkImage> getImprovedPermutationsImage() const {
  282. return fImprovedPermutationsImage;
  283. }
  284. const sk_sp<SkImage> getGradientImage() const { return fGradientImage; }
  285. #endif
  286. };
  287. /**
  288. * About the noise types : the difference between the first 2 is just minor tweaks to the
  289. * algorithm, they're not 2 entirely different noises. The output looks different, but once the
  290. * noise is generated in the [1, -1] range, the output is brought back in the [0, 1] range by
  291. * doing :
  292. * kFractalNoise_Type : noise * 0.5 + 0.5
  293. * kTurbulence_Type : abs(noise)
  294. * Very little differences between the 2 types, although you can tell the difference visually.
  295. * "Improved" is based on the Improved Perlin Noise algorithm described at
  296. * http://mrl.nyu.edu/~perlin/noise/. It is quite distinct from the other two, and the noise is
  297. * a 2D slice of a 3D noise texture. Minor changes to the Z coordinate will result in minor
  298. * changes to the noise, making it suitable for animated noise.
  299. */
  300. enum Type {
  301. kFractalNoise_Type,
  302. kTurbulence_Type,
  303. kImprovedNoise_Type,
  304. kLast_Type = kImprovedNoise_Type
  305. };
  306. static const int kMaxOctaves = 255; // numOctaves must be <= 0 and <= kMaxOctaves
  307. SkPerlinNoiseShaderImpl(SkPerlinNoiseShaderImpl::Type type, SkScalar baseFrequencyX,
  308. SkScalar baseFrequencyY, int numOctaves, SkScalar seed,
  309. const SkISize* tileSize);
  310. class PerlinNoiseShaderContext : public Context {
  311. public:
  312. PerlinNoiseShaderContext(const SkPerlinNoiseShaderImpl& shader, const ContextRec&);
  313. void shadeSpan(int x, int y, SkPMColor[], int count) override;
  314. private:
  315. SkPMColor shade(const SkPoint& point, StitchData& stitchData) const;
  316. SkScalar calculateTurbulenceValueForPoint(
  317. int channel,
  318. StitchData& stitchData, const SkPoint& point) const;
  319. SkScalar calculateImprovedNoiseValueForPoint(int channel, const SkPoint& point) const;
  320. SkScalar noise2D(int channel,
  321. const StitchData& stitchData, const SkPoint& noiseVector) const;
  322. SkMatrix fMatrix;
  323. PaintingData fPaintingData;
  324. typedef Context INHERITED;
  325. };
  326. #if SK_SUPPORT_GPU
  327. std::unique_ptr<GrFragmentProcessor> asFragmentProcessor(const GrFPArgs&) const override;
  328. #endif
  329. protected:
  330. void flatten(SkWriteBuffer&) const override;
  331. #ifdef SK_ENABLE_LEGACY_SHADERCONTEXT
  332. Context* onMakeContext(const ContextRec&, SkArenaAlloc*) const override;
  333. #endif
  334. private:
  335. SK_FLATTENABLE_HOOKS(SkPerlinNoiseShaderImpl)
  336. const SkPerlinNoiseShaderImpl::Type fType;
  337. const SkScalar fBaseFrequencyX;
  338. const SkScalar fBaseFrequencyY;
  339. const int fNumOctaves;
  340. const SkScalar fSeed;
  341. const SkISize fTileSize;
  342. const bool fStitchTiles;
  343. friend class ::SkPerlinNoiseShader;
  344. typedef SkShaderBase INHERITED;
  345. };
  346. namespace {
  347. // noiseValue is the color component's value (or color)
  348. // limitValue is the maximum perlin noise array index value allowed
  349. // newValue is the current noise dimension (either width or height)
  350. inline int checkNoise(int noiseValue, int limitValue, int newValue) {
  351. // If the noise value would bring us out of bounds of the current noise array while we are
  352. // stiching noise tiles together, wrap the noise around the current dimension of the noise to
  353. // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
  354. if (noiseValue >= limitValue) {
  355. noiseValue -= newValue;
  356. }
  357. return noiseValue;
  358. }
  359. inline SkScalar smoothCurve(SkScalar t) {
  360. return t * t * (3 - 2 * t);
  361. }
  362. } // end namespace
  363. SkPerlinNoiseShaderImpl::SkPerlinNoiseShaderImpl(SkPerlinNoiseShaderImpl::Type type,
  364. SkScalar baseFrequencyX,
  365. SkScalar baseFrequencyY,
  366. int numOctaves,
  367. SkScalar seed,
  368. const SkISize* tileSize)
  369. : fType(type)
  370. , fBaseFrequencyX(baseFrequencyX)
  371. , fBaseFrequencyY(baseFrequencyY)
  372. , fNumOctaves(numOctaves > kMaxOctaves ? kMaxOctaves : numOctaves/*[0,255] octaves allowed*/)
  373. , fSeed(seed)
  374. , fTileSize(nullptr == tileSize ? SkISize::Make(0, 0) : *tileSize)
  375. , fStitchTiles(!fTileSize.isEmpty())
  376. {
  377. SkASSERT(numOctaves >= 0 && numOctaves <= kMaxOctaves);
  378. SkASSERT(fBaseFrequencyX >= 0);
  379. SkASSERT(fBaseFrequencyY >= 0);
  380. }
  381. sk_sp<SkFlattenable> SkPerlinNoiseShaderImpl::CreateProc(SkReadBuffer& buffer) {
  382. Type type = buffer.read32LE(kLast_Type);
  383. SkScalar freqX = buffer.readScalar();
  384. SkScalar freqY = buffer.readScalar();
  385. int octaves = buffer.read32LE<int>(kMaxOctaves);
  386. SkScalar seed = buffer.readScalar();
  387. SkISize tileSize;
  388. tileSize.fWidth = buffer.readInt();
  389. tileSize.fHeight = buffer.readInt();
  390. switch (type) {
  391. case kFractalNoise_Type:
  392. return SkPerlinNoiseShader::MakeFractalNoise(freqX, freqY, octaves, seed, &tileSize);
  393. case kTurbulence_Type:
  394. return SkPerlinNoiseShader::MakeTurbulence(freqX, freqY, octaves, seed, &tileSize);
  395. case kImprovedNoise_Type:
  396. return SkPerlinNoiseShader::MakeImprovedNoise(freqX, freqY, octaves, seed);
  397. default:
  398. // Really shouldn't get here b.c. of earlier check on type
  399. buffer.validate(false);
  400. return nullptr;
  401. }
  402. }
  403. void SkPerlinNoiseShaderImpl::flatten(SkWriteBuffer& buffer) const {
  404. buffer.writeInt((int) fType);
  405. buffer.writeScalar(fBaseFrequencyX);
  406. buffer.writeScalar(fBaseFrequencyY);
  407. buffer.writeInt(fNumOctaves);
  408. buffer.writeScalar(fSeed);
  409. buffer.writeInt(fTileSize.fWidth);
  410. buffer.writeInt(fTileSize.fHeight);
  411. }
  412. SkScalar SkPerlinNoiseShaderImpl::PerlinNoiseShaderContext::noise2D(
  413. int channel, const StitchData& stitchData, const SkPoint& noiseVector) const {
  414. struct Noise {
  415. int noisePositionIntegerValue;
  416. int nextNoisePositionIntegerValue;
  417. SkScalar noisePositionFractionValue;
  418. Noise(SkScalar component)
  419. {
  420. SkScalar position = component + kPerlinNoise;
  421. noisePositionIntegerValue = SkScalarFloorToInt(position);
  422. noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
  423. nextNoisePositionIntegerValue = noisePositionIntegerValue + 1;
  424. }
  425. };
  426. Noise noiseX(noiseVector.x());
  427. Noise noiseY(noiseVector.y());
  428. SkScalar u, v;
  429. const SkPerlinNoiseShaderImpl& perlinNoiseShader = static_cast<const SkPerlinNoiseShaderImpl&>(fShader);
  430. // If stitching, adjust lattice points accordingly.
  431. if (perlinNoiseShader.fStitchTiles) {
  432. noiseX.noisePositionIntegerValue =
  433. checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
  434. noiseY.noisePositionIntegerValue =
  435. checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
  436. noiseX.nextNoisePositionIntegerValue =
  437. checkNoise(noiseX.nextNoisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
  438. noiseY.nextNoisePositionIntegerValue =
  439. checkNoise(noiseY.nextNoisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
  440. }
  441. noiseX.noisePositionIntegerValue &= kBlockMask;
  442. noiseY.noisePositionIntegerValue &= kBlockMask;
  443. noiseX.nextNoisePositionIntegerValue &= kBlockMask;
  444. noiseY.nextNoisePositionIntegerValue &= kBlockMask;
  445. int i = fPaintingData.fLatticeSelector[noiseX.noisePositionIntegerValue];
  446. int j = fPaintingData.fLatticeSelector[noiseX.nextNoisePositionIntegerValue];
  447. int b00 = (i + noiseY.noisePositionIntegerValue) & kBlockMask;
  448. int b10 = (j + noiseY.noisePositionIntegerValue) & kBlockMask;
  449. int b01 = (i + noiseY.nextNoisePositionIntegerValue) & kBlockMask;
  450. int b11 = (j + noiseY.nextNoisePositionIntegerValue) & kBlockMask;
  451. SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
  452. SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
  453. if (sx < 0 || sy < 0 || sx > 1 || sy > 1) {
  454. return 0; // Check for pathological inputs.
  455. }
  456. // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
  457. SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
  458. noiseY.noisePositionFractionValue); // Offset (0,0)
  459. u = fPaintingData.fGradient[channel][b00].dot(fractionValue);
  460. fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
  461. v = fPaintingData.fGradient[channel][b10].dot(fractionValue);
  462. SkScalar a = SkScalarInterp(u, v, sx);
  463. fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
  464. v = fPaintingData.fGradient[channel][b11].dot(fractionValue);
  465. fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
  466. u = fPaintingData.fGradient[channel][b01].dot(fractionValue);
  467. SkScalar b = SkScalarInterp(u, v, sx);
  468. return SkScalarInterp(a, b, sy);
  469. }
  470. SkScalar SkPerlinNoiseShaderImpl::PerlinNoiseShaderContext::calculateTurbulenceValueForPoint(
  471. int channel, StitchData& stitchData, const SkPoint& point) const {
  472. const SkPerlinNoiseShaderImpl& perlinNoiseShader = static_cast<const SkPerlinNoiseShaderImpl&>(fShader);
  473. if (perlinNoiseShader.fStitchTiles) {
  474. // Set up TurbulenceInitial stitch values.
  475. stitchData = fPaintingData.fStitchDataInit;
  476. }
  477. SkScalar turbulenceFunctionResult = 0;
  478. SkPoint noiseVector(SkPoint::Make(point.x() * fPaintingData.fBaseFrequency.fX,
  479. point.y() * fPaintingData.fBaseFrequency.fY));
  480. SkScalar ratio = SK_Scalar1;
  481. for (int octave = 0; octave < perlinNoiseShader.fNumOctaves; ++octave) {
  482. SkScalar noise = noise2D(channel, stitchData, noiseVector);
  483. SkScalar numer = (perlinNoiseShader.fType == kFractalNoise_Type) ?
  484. noise : SkScalarAbs(noise);
  485. turbulenceFunctionResult += numer / ratio;
  486. noiseVector.fX *= 2;
  487. noiseVector.fY *= 2;
  488. ratio *= 2;
  489. if (perlinNoiseShader.fStitchTiles) {
  490. // Update stitch values
  491. stitchData = StitchData(SkIntToScalar(stitchData.fWidth) * 2,
  492. SkIntToScalar(stitchData.fHeight) * 2);
  493. }
  494. }
  495. // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
  496. // by fractalNoise and (turbulenceFunctionResult) by turbulence.
  497. if (perlinNoiseShader.fType == kFractalNoise_Type) {
  498. turbulenceFunctionResult = SkScalarHalf(turbulenceFunctionResult + 1);
  499. }
  500. if (channel == 3) { // Scale alpha by paint value
  501. turbulenceFunctionResult *= SkIntToScalar(getPaintAlpha()) / 255;
  502. }
  503. // Clamp result
  504. return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
  505. }
  506. ////////////////////////////////////////////////////////////////////////////////////////////////////
  507. // Improved Perlin Noise based on Java implementation found at http://mrl.nyu.edu/~perlin/noise/
  508. static SkScalar fade(SkScalar t) {
  509. return t * t * t * (t * (t * 6 - 15) + 10);
  510. }
  511. static SkScalar lerp(SkScalar t, SkScalar a, SkScalar b) {
  512. return a + t * (b - a);
  513. }
  514. static SkScalar grad(int hash, SkScalar x, SkScalar y, SkScalar z) {
  515. int h = hash & 15;
  516. SkScalar u = h < 8 ? x : y;
  517. SkScalar v = h < 4 ? y : h == 12 || h == 14 ? x : z;
  518. return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
  519. }
  520. SkScalar SkPerlinNoiseShaderImpl::PerlinNoiseShaderContext::calculateImprovedNoiseValueForPoint(
  521. int channel, const SkPoint& point) const {
  522. const SkPerlinNoiseShaderImpl& perlinNoiseShader = static_cast<const SkPerlinNoiseShaderImpl&>(fShader);
  523. SkScalar x = point.fX * perlinNoiseShader.fBaseFrequencyX;
  524. SkScalar y = point.fY * perlinNoiseShader.fBaseFrequencyY;
  525. // z offset between different channels, chosen arbitrarily
  526. static const SkScalar CHANNEL_DELTA = 1000.0f;
  527. SkScalar z = channel * CHANNEL_DELTA + perlinNoiseShader.fSeed;
  528. SkScalar result = 0;
  529. SkScalar ratio = SK_Scalar1;
  530. for (int i = 0; i < perlinNoiseShader.fNumOctaves; i++) {
  531. int X = SkScalarFloorToInt(x) & 255;
  532. int Y = SkScalarFloorToInt(y) & 255;
  533. int Z = SkScalarFloorToInt(z) & 255;
  534. SkScalar px = x - SkScalarFloorToScalar(x);
  535. SkScalar py = y - SkScalarFloorToScalar(y);
  536. SkScalar pz = z - SkScalarFloorToScalar(z);
  537. SkScalar u = fade(px);
  538. SkScalar v = fade(py);
  539. SkScalar w = fade(pz);
  540. uint8_t* permutations = improved_noise_permutations;
  541. int A = permutations[X] + Y;
  542. int AA = permutations[A] + Z;
  543. int AB = permutations[A + 1] + Z;
  544. int B = permutations[X + 1] + Y;
  545. int BA = permutations[B] + Z;
  546. int BB = permutations[B + 1] + Z;
  547. result += lerp(w, lerp(v, lerp(u, grad(permutations[AA ], px , py , pz ),
  548. grad(permutations[BA ], px - 1, py , pz )),
  549. lerp(u, grad(permutations[AB ], px , py - 1, pz ),
  550. grad(permutations[BB ], px - 1, py - 1, pz ))),
  551. lerp(v, lerp(u, grad(permutations[AA + 1], px , py , pz - 1),
  552. grad(permutations[BA + 1], px - 1, py , pz - 1)),
  553. lerp(u, grad(permutations[AB + 1], px , py - 1, pz - 1),
  554. grad(permutations[BB + 1], px - 1, py - 1, pz - 1)))) /
  555. ratio;
  556. x *= 2;
  557. y *= 2;
  558. ratio *= 2;
  559. }
  560. result = SkScalarClampMax((result + 1.0f) / 2.0f, 1.0f);
  561. return result;
  562. }
  563. ////////////////////////////////////////////////////////////////////////////////////////////////////
  564. SkPMColor SkPerlinNoiseShaderImpl::PerlinNoiseShaderContext::shade(
  565. const SkPoint& point, StitchData& stitchData) const {
  566. const SkPerlinNoiseShaderImpl& perlinNoiseShader = static_cast<const SkPerlinNoiseShaderImpl&>(fShader);
  567. SkPoint newPoint;
  568. fMatrix.mapPoints(&newPoint, &point, 1);
  569. newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
  570. newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
  571. U8CPU rgba[4];
  572. for (int channel = 3; channel >= 0; --channel) {
  573. SkScalar value;
  574. if (perlinNoiseShader.fType == kImprovedNoise_Type) {
  575. value = calculateImprovedNoiseValueForPoint(channel, newPoint);
  576. }
  577. else {
  578. value = calculateTurbulenceValueForPoint(channel, stitchData, newPoint);
  579. }
  580. rgba[channel] = SkScalarFloorToInt(255 * value);
  581. }
  582. return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
  583. }
  584. #ifdef SK_ENABLE_LEGACY_SHADERCONTEXT
  585. SkShaderBase::Context* SkPerlinNoiseShaderImpl::onMakeContext(const ContextRec& rec,
  586. SkArenaAlloc* alloc) const {
  587. // should we pay attention to rec's device-colorspace?
  588. return alloc->make<PerlinNoiseShaderContext>(*this, rec);
  589. }
  590. #endif
  591. static inline SkMatrix total_matrix(const SkShaderBase::ContextRec& rec,
  592. const SkShaderBase& shader) {
  593. SkMatrix matrix = SkMatrix::Concat(*rec.fMatrix, shader.getLocalMatrix());
  594. if (rec.fLocalMatrix) {
  595. matrix.preConcat(*rec.fLocalMatrix);
  596. }
  597. return matrix;
  598. }
  599. SkPerlinNoiseShaderImpl::PerlinNoiseShaderContext::PerlinNoiseShaderContext(
  600. const SkPerlinNoiseShaderImpl& shader, const ContextRec& rec)
  601. : INHERITED(shader, rec)
  602. , fMatrix(total_matrix(rec, shader)) // used for temp storage, adjusted below
  603. , fPaintingData(shader.fTileSize, shader.fSeed, shader.fBaseFrequencyX,
  604. shader.fBaseFrequencyY, fMatrix)
  605. {
  606. // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
  607. // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
  608. fMatrix.setTranslate(-fMatrix.getTranslateX() + SK_Scalar1,
  609. -fMatrix.getTranslateY() + SK_Scalar1);
  610. }
  611. void SkPerlinNoiseShaderImpl::PerlinNoiseShaderContext::shadeSpan(
  612. int x, int y, SkPMColor result[], int count) {
  613. SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
  614. StitchData stitchData;
  615. for (int i = 0; i < count; ++i) {
  616. result[i] = shade(point, stitchData);
  617. point.fX += SK_Scalar1;
  618. }
  619. }
  620. /////////////////////////////////////////////////////////////////////
  621. #if SK_SUPPORT_GPU
  622. class GrGLPerlinNoise : public GrGLSLFragmentProcessor {
  623. public:
  624. void emitCode(EmitArgs&) override;
  625. static inline void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder* b);
  626. protected:
  627. void onSetData(const GrGLSLProgramDataManager&, const GrFragmentProcessor&) override;
  628. private:
  629. GrGLSLProgramDataManager::UniformHandle fStitchDataUni;
  630. GrGLSLProgramDataManager::UniformHandle fBaseFrequencyUni;
  631. typedef GrGLSLFragmentProcessor INHERITED;
  632. };
  633. /////////////////////////////////////////////////////////////////////
  634. class GrPerlinNoise2Effect : public GrFragmentProcessor {
  635. public:
  636. static std::unique_ptr<GrFragmentProcessor> Make(
  637. SkPerlinNoiseShaderImpl::Type type, int numOctaves, bool stitchTiles,
  638. std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> paintingData,
  639. sk_sp<GrTextureProxy> permutationsProxy, sk_sp<GrTextureProxy> noiseProxy,
  640. const SkMatrix& matrix) {
  641. return std::unique_ptr<GrFragmentProcessor>(new GrPerlinNoise2Effect(
  642. type, numOctaves, stitchTiles, std::move(paintingData),
  643. std::move(permutationsProxy), std::move(noiseProxy), matrix));
  644. }
  645. const char* name() const override { return "PerlinNoise"; }
  646. std::unique_ptr<GrFragmentProcessor> clone() const override {
  647. return std::unique_ptr<GrFragmentProcessor>(new GrPerlinNoise2Effect(*this));
  648. }
  649. const SkPerlinNoiseShaderImpl::StitchData& stitchData() const { return fPaintingData->fStitchDataInit; }
  650. SkPerlinNoiseShaderImpl::Type type() const { return fType; }
  651. bool stitchTiles() const { return fStitchTiles; }
  652. const SkVector& baseFrequency() const { return fPaintingData->fBaseFrequency; }
  653. int numOctaves() const { return fNumOctaves; }
  654. const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
  655. private:
  656. GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
  657. return new GrGLPerlinNoise;
  658. }
  659. virtual void onGetGLSLProcessorKey(const GrShaderCaps& caps,
  660. GrProcessorKeyBuilder* b) const override {
  661. GrGLPerlinNoise::GenKey(*this, caps, b);
  662. }
  663. bool onIsEqual(const GrFragmentProcessor& sBase) const override {
  664. const GrPerlinNoise2Effect& s = sBase.cast<GrPerlinNoise2Effect>();
  665. return fType == s.fType &&
  666. fPaintingData->fBaseFrequency == s.fPaintingData->fBaseFrequency &&
  667. fNumOctaves == s.fNumOctaves &&
  668. fStitchTiles == s.fStitchTiles &&
  669. fPaintingData->fStitchDataInit == s.fPaintingData->fStitchDataInit;
  670. }
  671. GrPerlinNoise2Effect(SkPerlinNoiseShaderImpl::Type type, int numOctaves, bool stitchTiles,
  672. std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> paintingData,
  673. sk_sp<GrTextureProxy> permutationsProxy,
  674. sk_sp<GrTextureProxy> noiseProxy,
  675. const SkMatrix& matrix)
  676. : INHERITED(kGrPerlinNoise2Effect_ClassID, kNone_OptimizationFlags)
  677. , fType(type)
  678. , fNumOctaves(numOctaves)
  679. , fStitchTiles(stitchTiles)
  680. , fPermutationsSampler(std::move(permutationsProxy))
  681. , fNoiseSampler(std::move(noiseProxy))
  682. , fPaintingData(std::move(paintingData)) {
  683. this->setTextureSamplerCnt(2);
  684. fCoordTransform = GrCoordTransform(matrix);
  685. this->addCoordTransform(&fCoordTransform);
  686. }
  687. GrPerlinNoise2Effect(const GrPerlinNoise2Effect& that)
  688. : INHERITED(kGrPerlinNoise2Effect_ClassID, kNone_OptimizationFlags)
  689. , fType(that.fType)
  690. , fCoordTransform(that.fCoordTransform)
  691. , fNumOctaves(that.fNumOctaves)
  692. , fStitchTiles(that.fStitchTiles)
  693. , fPermutationsSampler(that.fPermutationsSampler)
  694. , fNoiseSampler(that.fNoiseSampler)
  695. , fPaintingData(new SkPerlinNoiseShaderImpl::PaintingData(*that.fPaintingData)) {
  696. this->setTextureSamplerCnt(2);
  697. this->addCoordTransform(&fCoordTransform);
  698. }
  699. const TextureSampler& onTextureSampler(int i) const override {
  700. return IthTextureSampler(i, fPermutationsSampler, fNoiseSampler);
  701. }
  702. GR_DECLARE_FRAGMENT_PROCESSOR_TEST
  703. SkPerlinNoiseShaderImpl::Type fType;
  704. GrCoordTransform fCoordTransform;
  705. int fNumOctaves;
  706. bool fStitchTiles;
  707. TextureSampler fPermutationsSampler;
  708. TextureSampler fNoiseSampler;
  709. std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> fPaintingData;
  710. typedef GrFragmentProcessor INHERITED;
  711. };
  712. /////////////////////////////////////////////////////////////////////
  713. GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrPerlinNoise2Effect);
  714. #if GR_TEST_UTILS
  715. std::unique_ptr<GrFragmentProcessor> GrPerlinNoise2Effect::TestCreate(GrProcessorTestData* d) {
  716. int numOctaves = d->fRandom->nextRangeU(2, 10);
  717. bool stitchTiles = d->fRandom->nextBool();
  718. SkScalar seed = SkIntToScalar(d->fRandom->nextU());
  719. SkISize tileSize = SkISize::Make(d->fRandom->nextRangeU(4, 4096),
  720. d->fRandom->nextRangeU(4, 4096));
  721. SkScalar baseFrequencyX = d->fRandom->nextRangeScalar(0.01f,
  722. 0.99f);
  723. SkScalar baseFrequencyY = d->fRandom->nextRangeScalar(0.01f,
  724. 0.99f);
  725. sk_sp<SkShader> shader(d->fRandom->nextBool() ?
  726. SkPerlinNoiseShader::MakeFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
  727. stitchTiles ? &tileSize : nullptr) :
  728. SkPerlinNoiseShader::MakeTurbulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
  729. stitchTiles ? &tileSize : nullptr));
  730. GrTest::TestAsFPArgs asFPArgs(d);
  731. return as_SB(shader)->asFragmentProcessor(asFPArgs.args());
  732. }
  733. #endif
  734. void GrGLPerlinNoise::emitCode(EmitArgs& args) {
  735. const GrPerlinNoise2Effect& pne = args.fFp.cast<GrPerlinNoise2Effect>();
  736. GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
  737. GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
  738. SkString vCoords = fragBuilder->ensureCoords2D(args.fTransformedCoords[0]);
  739. fBaseFrequencyUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf2_GrSLType,
  740. "baseFrequency");
  741. const char* baseFrequencyUni = uniformHandler->getUniformCStr(fBaseFrequencyUni);
  742. const char* stitchDataUni = nullptr;
  743. if (pne.stitchTiles()) {
  744. fStitchDataUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf2_GrSLType,
  745. "stitchData");
  746. stitchDataUni = uniformHandler->getUniformCStr(fStitchDataUni);
  747. }
  748. // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
  749. const char* chanCoordR = "0.125";
  750. const char* chanCoordG = "0.375";
  751. const char* chanCoordB = "0.625";
  752. const char* chanCoordA = "0.875";
  753. const char* chanCoord = "chanCoord";
  754. const char* stitchData = "stitchData";
  755. const char* ratio = "ratio";
  756. const char* noiseVec = "noiseVec";
  757. const char* noiseSmooth = "noiseSmooth";
  758. const char* floorVal = "floorVal";
  759. const char* fractVal = "fractVal";
  760. const char* uv = "uv";
  761. const char* ab = "ab";
  762. const char* latticeIdx = "latticeIdx";
  763. const char* bcoords = "bcoords";
  764. const char* lattice = "lattice";
  765. const char* inc8bit = "0.00390625"; // 1.0 / 256.0
  766. // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
  767. // [-1,1] vector and perform a dot product between that vector and the provided vector.
  768. const char* dotLattice = "dot(((%s.ga + %s.rb * half2(%s)) * half2(2.0) - half2(1.0)), %s);";
  769. // Add noise function
  770. const GrShaderVar gPerlinNoiseArgs[] = {
  771. GrShaderVar(chanCoord, kHalf_GrSLType),
  772. GrShaderVar(noiseVec, kHalf2_GrSLType)
  773. };
  774. const GrShaderVar gPerlinNoiseStitchArgs[] = {
  775. GrShaderVar(chanCoord, kHalf_GrSLType),
  776. GrShaderVar(noiseVec, kHalf2_GrSLType),
  777. GrShaderVar(stitchData, kHalf2_GrSLType)
  778. };
  779. SkString noiseCode;
  780. noiseCode.appendf("\thalf4 %s;\n", floorVal);
  781. noiseCode.appendf("\t%s.xy = floor(%s);\n", floorVal, noiseVec);
  782. noiseCode.appendf("\t%s.zw = %s.xy + half2(1.0);\n", floorVal, floorVal);
  783. noiseCode.appendf("\thalf2 %s = fract(%s);\n", fractVal, noiseVec);
  784. // smooth curve : t * t * (3 - 2 * t)
  785. noiseCode.appendf("\n\thalf2 %s = %s * %s * (half2(3.0) - half2(2.0) * %s);",
  786. noiseSmooth, fractVal, fractVal, fractVal);
  787. // Adjust frequencies if we're stitching tiles
  788. if (pne.stitchTiles()) {
  789. noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
  790. floorVal, stitchData, floorVal, stitchData);
  791. noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }",
  792. floorVal, stitchData, floorVal, stitchData);
  793. noiseCode.appendf("\n\tif(%s.z >= %s.x) { %s.z -= %s.x; }",
  794. floorVal, stitchData, floorVal, stitchData);
  795. noiseCode.appendf("\n\tif(%s.w >= %s.y) { %s.w -= %s.y; }",
  796. floorVal, stitchData, floorVal, stitchData);
  797. }
  798. // Get texture coordinates and normalize
  799. noiseCode.appendf("\n\t%s = fract(floor(mod(%s, 256.0)) / half4(256.0));\n",
  800. floorVal, floorVal);
  801. // Get permutation for x
  802. {
  803. SkString xCoords("");
  804. xCoords.appendf("half2(%s.x, 0.5)", floorVal);
  805. noiseCode.appendf("\n\thalf2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
  806. fragBuilder->appendTextureLookup(&noiseCode, args.fTexSamplers[0], xCoords.c_str(),
  807. kHalf2_GrSLType);
  808. noiseCode.append(".r;");
  809. }
  810. // Get permutation for x + 1
  811. {
  812. SkString xCoords("");
  813. xCoords.appendf("half2(%s.z, 0.5)", floorVal);
  814. noiseCode.appendf("\n\t%s.y = ", latticeIdx);
  815. fragBuilder->appendTextureLookup(&noiseCode, args.fTexSamplers[0], xCoords.c_str(),
  816. kHalf2_GrSLType);
  817. noiseCode.append(".r;");
  818. }
  819. #if defined(SK_BUILD_FOR_ANDROID)
  820. // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
  821. // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
  822. // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
  823. // (or 0.484368 here). The following rounding operation prevents these precision issues from
  824. // affecting the result of the noise by making sure that we only have multiples of 1/255.
  825. // (Note that 1/255 is about 0.003921569, which is the value used here).
  826. noiseCode.appendf("\n\t%s = floor(%s * half2(255.0) + half2(0.5)) * half2(0.003921569);",
  827. latticeIdx, latticeIdx);
  828. #endif
  829. // Get (x,y) coordinates with the permutated x
  830. noiseCode.appendf("\n\thalf4 %s = fract(%s.xyxy + %s.yyww);", bcoords, latticeIdx, floorVal);
  831. noiseCode.appendf("\n\n\thalf2 %s;", uv);
  832. // Compute u, at offset (0,0)
  833. {
  834. SkString latticeCoords("");
  835. latticeCoords.appendf("half2(%s.x, %s)", bcoords, chanCoord);
  836. noiseCode.appendf("\n\thalf4 %s = ", lattice);
  837. fragBuilder->appendTextureLookup(&noiseCode, args.fTexSamplers[1], latticeCoords.c_str(),
  838. kHalf2_GrSLType);
  839. noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
  840. noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
  841. }
  842. noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
  843. // Compute v, at offset (-1,0)
  844. {
  845. SkString latticeCoords("");
  846. latticeCoords.appendf("half2(%s.y, %s)", bcoords, chanCoord);
  847. noiseCode.append("\n\tlattice = ");
  848. fragBuilder->appendTextureLookup(&noiseCode, args.fTexSamplers[1], latticeCoords.c_str(),
  849. kHalf2_GrSLType);
  850. noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
  851. noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
  852. }
  853. // Compute 'a' as a linear interpolation of 'u' and 'v'
  854. noiseCode.appendf("\n\thalf2 %s;", ab);
  855. noiseCode.appendf("\n\t%s.x = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
  856. noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
  857. // Compute v, at offset (-1,-1)
  858. {
  859. SkString latticeCoords("");
  860. latticeCoords.appendf("half2(%s.w, %s)", bcoords, chanCoord);
  861. noiseCode.append("\n\tlattice = ");
  862. fragBuilder->appendTextureLookup(&noiseCode, args.fTexSamplers[1], latticeCoords.c_str(),
  863. kHalf2_GrSLType);
  864. noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
  865. noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
  866. }
  867. noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
  868. // Compute u, at offset (0,-1)
  869. {
  870. SkString latticeCoords("");
  871. latticeCoords.appendf("half2(%s.z, %s)", bcoords, chanCoord);
  872. noiseCode.append("\n\tlattice = ");
  873. fragBuilder->appendTextureLookup(&noiseCode, args.fTexSamplers[1], latticeCoords.c_str(),
  874. kHalf2_GrSLType);
  875. noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
  876. noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
  877. }
  878. // Compute 'b' as a linear interpolation of 'u' and 'v'
  879. noiseCode.appendf("\n\t%s.y = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
  880. // Compute the noise as a linear interpolation of 'a' and 'b'
  881. noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
  882. SkString noiseFuncName;
  883. if (pne.stitchTiles()) {
  884. fragBuilder->emitFunction(kHalf_GrSLType,
  885. "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
  886. gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
  887. } else {
  888. fragBuilder->emitFunction(kHalf_GrSLType,
  889. "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
  890. gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
  891. }
  892. // There are rounding errors if the floor operation is not performed here
  893. fragBuilder->codeAppendf("\n\t\thalf2 %s = half2(floor(%s.xy) * %s);",
  894. noiseVec, vCoords.c_str(), baseFrequencyUni);
  895. // Clear the color accumulator
  896. fragBuilder->codeAppendf("\n\t\t%s = half4(0.0);", args.fOutputColor);
  897. if (pne.stitchTiles()) {
  898. // Set up TurbulenceInitial stitch values.
  899. fragBuilder->codeAppendf("\n\t\thalf2 %s = %s;", stitchData, stitchDataUni);
  900. }
  901. fragBuilder->codeAppendf("\n\t\thalf %s = 1.0;", ratio);
  902. // Loop over all octaves
  903. fragBuilder->codeAppendf("for (int octave = 0; octave < %d; ++octave) {", pne.numOctaves());
  904. fragBuilder->codeAppendf("\n\t\t\t%s += ", args.fOutputColor);
  905. if (pne.type() != SkPerlinNoiseShaderImpl::kFractalNoise_Type) {
  906. fragBuilder->codeAppend("abs(");
  907. }
  908. if (pne.stitchTiles()) {
  909. fragBuilder->codeAppendf(
  910. "half4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
  911. "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
  912. noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
  913. noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
  914. noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
  915. noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
  916. } else {
  917. fragBuilder->codeAppendf(
  918. "half4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
  919. "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
  920. noiseFuncName.c_str(), chanCoordR, noiseVec,
  921. noiseFuncName.c_str(), chanCoordG, noiseVec,
  922. noiseFuncName.c_str(), chanCoordB, noiseVec,
  923. noiseFuncName.c_str(), chanCoordA, noiseVec);
  924. }
  925. if (pne.type() != SkPerlinNoiseShaderImpl::kFractalNoise_Type) {
  926. fragBuilder->codeAppendf(")"); // end of "abs("
  927. }
  928. fragBuilder->codeAppendf(" * %s;", ratio);
  929. fragBuilder->codeAppendf("\n\t\t\t%s *= half2(2.0);", noiseVec);
  930. fragBuilder->codeAppendf("\n\t\t\t%s *= 0.5;", ratio);
  931. if (pne.stitchTiles()) {
  932. fragBuilder->codeAppendf("\n\t\t\t%s *= half2(2.0);", stitchData);
  933. }
  934. fragBuilder->codeAppend("\n\t\t}"); // end of the for loop on octaves
  935. if (pne.type() == SkPerlinNoiseShaderImpl::kFractalNoise_Type) {
  936. // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
  937. // by fractalNoise and (turbulenceFunctionResult) by turbulence.
  938. fragBuilder->codeAppendf("\n\t\t%s = %s * half4(0.5) + half4(0.5);",
  939. args.fOutputColor,args.fOutputColor);
  940. }
  941. // Clamp values
  942. fragBuilder->codeAppendf("\n\t\t%s = saturate(%s);", args.fOutputColor, args.fOutputColor);
  943. // Pre-multiply the result
  944. fragBuilder->codeAppendf("\n\t\t%s = half4(%s.rgb * %s.aaa, %s.a);\n",
  945. args.fOutputColor, args.fOutputColor,
  946. args.fOutputColor, args.fOutputColor);
  947. }
  948. void GrGLPerlinNoise::GenKey(const GrProcessor& processor, const GrShaderCaps&,
  949. GrProcessorKeyBuilder* b) {
  950. const GrPerlinNoise2Effect& turbulence = processor.cast<GrPerlinNoise2Effect>();
  951. uint32_t key = turbulence.numOctaves();
  952. key = key << 3; // Make room for next 3 bits
  953. switch (turbulence.type()) {
  954. case SkPerlinNoiseShaderImpl::kFractalNoise_Type:
  955. key |= 0x1;
  956. break;
  957. case SkPerlinNoiseShaderImpl::kTurbulence_Type:
  958. key |= 0x2;
  959. break;
  960. default:
  961. // leave key at 0
  962. break;
  963. }
  964. if (turbulence.stitchTiles()) {
  965. key |= 0x4; // Flip the 3rd bit if tile stitching is on
  966. }
  967. b->add32(key);
  968. }
  969. void GrGLPerlinNoise::onSetData(const GrGLSLProgramDataManager& pdman,
  970. const GrFragmentProcessor& processor) {
  971. INHERITED::onSetData(pdman, processor);
  972. const GrPerlinNoise2Effect& turbulence = processor.cast<GrPerlinNoise2Effect>();
  973. const SkVector& baseFrequency = turbulence.baseFrequency();
  974. pdman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
  975. if (turbulence.stitchTiles()) {
  976. const SkPerlinNoiseShaderImpl::StitchData& stitchData = turbulence.stitchData();
  977. pdman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
  978. SkIntToScalar(stitchData.fHeight));
  979. }
  980. }
  981. /////////////////////////////////////////////////////////////////////
  982. class GrGLImprovedPerlinNoise : public GrGLSLFragmentProcessor {
  983. public:
  984. void emitCode(EmitArgs&) override;
  985. static inline void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder*);
  986. protected:
  987. void onSetData(const GrGLSLProgramDataManager&, const GrFragmentProcessor&) override;
  988. private:
  989. GrGLSLProgramDataManager::UniformHandle fZUni;
  990. GrGLSLProgramDataManager::UniformHandle fBaseFrequencyUni;
  991. typedef GrGLSLFragmentProcessor INHERITED;
  992. };
  993. /////////////////////////////////////////////////////////////////////
  994. class GrImprovedPerlinNoiseEffect : public GrFragmentProcessor {
  995. public:
  996. static std::unique_ptr<GrFragmentProcessor> Make(
  997. int octaves, SkScalar z,
  998. std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> paintingData,
  999. sk_sp<GrTextureProxy> permutationsProxy, sk_sp<GrTextureProxy> gradientProxy,
  1000. const SkMatrix& matrix) {
  1001. return std::unique_ptr<GrFragmentProcessor>(new GrImprovedPerlinNoiseEffect(
  1002. octaves, z, std::move(paintingData), std::move(permutationsProxy),
  1003. std::move(gradientProxy), matrix));
  1004. }
  1005. const char* name() const override { return "ImprovedPerlinNoise"; }
  1006. std::unique_ptr<GrFragmentProcessor> clone() const override {
  1007. return std::unique_ptr<GrFragmentProcessor>(new GrImprovedPerlinNoiseEffect(*this));
  1008. }
  1009. const SkVector& baseFrequency() const { return fPaintingData->fBaseFrequency; }
  1010. SkScalar z() const { return fZ; }
  1011. int octaves() const { return fOctaves; }
  1012. const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
  1013. private:
  1014. GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
  1015. return new GrGLImprovedPerlinNoise;
  1016. }
  1017. void onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const override {
  1018. GrGLImprovedPerlinNoise::GenKey(*this, caps, b);
  1019. }
  1020. bool onIsEqual(const GrFragmentProcessor& sBase) const override {
  1021. const GrImprovedPerlinNoiseEffect& s = sBase.cast<GrImprovedPerlinNoiseEffect>();
  1022. return fZ == fZ &&
  1023. fPaintingData->fBaseFrequency == s.fPaintingData->fBaseFrequency;
  1024. }
  1025. GrImprovedPerlinNoiseEffect(int octaves, SkScalar z,
  1026. std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> paintingData,
  1027. sk_sp<GrTextureProxy> permutationsProxy,
  1028. sk_sp<GrTextureProxy> gradientProxy,
  1029. const SkMatrix& matrix)
  1030. : INHERITED(kGrImprovedPerlinNoiseEffect_ClassID, kNone_OptimizationFlags)
  1031. , fOctaves(octaves)
  1032. , fZ(z)
  1033. , fPermutationsSampler(std::move(permutationsProxy))
  1034. , fGradientSampler(std::move(gradientProxy))
  1035. , fPaintingData(std::move(paintingData)) {
  1036. this->setTextureSamplerCnt(2);
  1037. fCoordTransform = GrCoordTransform(matrix);
  1038. this->addCoordTransform(&fCoordTransform);
  1039. }
  1040. GrImprovedPerlinNoiseEffect(const GrImprovedPerlinNoiseEffect& that)
  1041. : INHERITED(kGrImprovedPerlinNoiseEffect_ClassID, kNone_OptimizationFlags)
  1042. , fCoordTransform(that.fCoordTransform)
  1043. , fOctaves(that.fOctaves)
  1044. , fZ(that.fZ)
  1045. , fPermutationsSampler(that.fPermutationsSampler)
  1046. , fGradientSampler(that.fGradientSampler)
  1047. , fPaintingData(new SkPerlinNoiseShaderImpl::PaintingData(*that.fPaintingData)) {
  1048. this->setTextureSamplerCnt(2);
  1049. this->addCoordTransform(&fCoordTransform);
  1050. }
  1051. const TextureSampler& onTextureSampler(int i) const override {
  1052. return IthTextureSampler(i, fPermutationsSampler, fGradientSampler);
  1053. }
  1054. GR_DECLARE_FRAGMENT_PROCESSOR_TEST
  1055. GrCoordTransform fCoordTransform;
  1056. int fOctaves;
  1057. SkScalar fZ;
  1058. TextureSampler fPermutationsSampler;
  1059. TextureSampler fGradientSampler;
  1060. std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> fPaintingData;
  1061. typedef GrFragmentProcessor INHERITED;
  1062. };
  1063. /////////////////////////////////////////////////////////////////////
  1064. GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrImprovedPerlinNoiseEffect);
  1065. #if GR_TEST_UTILS
  1066. std::unique_ptr<GrFragmentProcessor> GrImprovedPerlinNoiseEffect::TestCreate(
  1067. GrProcessorTestData* d) {
  1068. SkScalar baseFrequencyX = d->fRandom->nextRangeScalar(0.01f,
  1069. 0.99f);
  1070. SkScalar baseFrequencyY = d->fRandom->nextRangeScalar(0.01f,
  1071. 0.99f);
  1072. int numOctaves = d->fRandom->nextRangeU(2, 10);
  1073. SkScalar z = SkIntToScalar(d->fRandom->nextU());
  1074. sk_sp<SkShader> shader(SkPerlinNoiseShader::MakeImprovedNoise(baseFrequencyX,
  1075. baseFrequencyY,
  1076. numOctaves,
  1077. z));
  1078. GrTest::TestAsFPArgs asFPArgs(d);
  1079. return as_SB(shader)->asFragmentProcessor(asFPArgs.args());
  1080. }
  1081. #endif
  1082. void GrGLImprovedPerlinNoise::emitCode(EmitArgs& args) {
  1083. const GrImprovedPerlinNoiseEffect& pne = args.fFp.cast<GrImprovedPerlinNoiseEffect>();
  1084. GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
  1085. GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
  1086. SkString vCoords = fragBuilder->ensureCoords2D(args.fTransformedCoords[0]);
  1087. fBaseFrequencyUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf2_GrSLType,
  1088. "baseFrequency");
  1089. const char* baseFrequencyUni = uniformHandler->getUniformCStr(fBaseFrequencyUni);
  1090. fZUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType, "z");
  1091. const char* zUni = uniformHandler->getUniformCStr(fZUni);
  1092. // fade function
  1093. const GrShaderVar fadeArgs[] = {
  1094. GrShaderVar("t", kHalf3_GrSLType)
  1095. };
  1096. SkString fadeFuncName;
  1097. fragBuilder->emitFunction(kHalf3_GrSLType, "fade", SK_ARRAY_COUNT(fadeArgs),
  1098. fadeArgs,
  1099. "return t * t * t * (t * (t * 6.0 - 15.0) + 10.0);",
  1100. &fadeFuncName);
  1101. // perm function
  1102. const GrShaderVar permArgs[] = {
  1103. GrShaderVar("x", kHalf_GrSLType)
  1104. };
  1105. SkString permFuncName;
  1106. SkString permCode("return ");
  1107. // FIXME even though I'm creating these textures with kRepeat_TileMode, they're clamped. Not
  1108. // sure why. Using fract() (here and the next texture lookup) as a workaround.
  1109. fragBuilder->appendTextureLookup(&permCode, args.fTexSamplers[0], "float2(fract(x / 256.0), 0.0)",
  1110. kHalf2_GrSLType);
  1111. permCode.append(".r * 255.0;");
  1112. fragBuilder->emitFunction(kHalf_GrSLType, "perm", SK_ARRAY_COUNT(permArgs), permArgs,
  1113. permCode.c_str(), &permFuncName);
  1114. // grad function
  1115. const GrShaderVar gradArgs[] = {
  1116. GrShaderVar("x", kHalf_GrSLType),
  1117. GrShaderVar("p", kHalf3_GrSLType)
  1118. };
  1119. SkString gradFuncName;
  1120. SkString gradCode("return half(dot(");
  1121. fragBuilder->appendTextureLookup(&gradCode, args.fTexSamplers[1], "float2(fract(x / 16.0), 0.0)",
  1122. kHalf2_GrSLType);
  1123. gradCode.append(".rgb * 255.0 - float3(1.0), p));");
  1124. fragBuilder->emitFunction(kHalf_GrSLType, "grad", SK_ARRAY_COUNT(gradArgs), gradArgs,
  1125. gradCode.c_str(), &gradFuncName);
  1126. // lerp function
  1127. const GrShaderVar lerpArgs[] = {
  1128. GrShaderVar("a", kHalf_GrSLType),
  1129. GrShaderVar("b", kHalf_GrSLType),
  1130. GrShaderVar("w", kHalf_GrSLType)
  1131. };
  1132. SkString lerpFuncName;
  1133. fragBuilder->emitFunction(kHalf_GrSLType, "lerp", SK_ARRAY_COUNT(lerpArgs), lerpArgs,
  1134. "return a + w * (b - a);", &lerpFuncName);
  1135. // noise function
  1136. const GrShaderVar noiseArgs[] = {
  1137. GrShaderVar("p", kHalf3_GrSLType),
  1138. };
  1139. SkString noiseFuncName;
  1140. SkString noiseCode;
  1141. noiseCode.append("half3 P = mod(floor(p), 256.0);");
  1142. noiseCode.append("p -= floor(p);");
  1143. noiseCode.appendf("half3 f = %s(p);", fadeFuncName.c_str());
  1144. noiseCode.appendf("half A = %s(P.x) + P.y;", permFuncName.c_str());
  1145. noiseCode.appendf("half AA = %s(A) + P.z;", permFuncName.c_str());
  1146. noiseCode.appendf("half AB = %s(A + 1.0) + P.z;", permFuncName.c_str());
  1147. noiseCode.appendf("half B = %s(P.x + 1.0) + P.y;", permFuncName.c_str());
  1148. noiseCode.appendf("half BA = %s(B) + P.z;", permFuncName.c_str());
  1149. noiseCode.appendf("half BB = %s(B + 1.0) + P.z;", permFuncName.c_str());
  1150. noiseCode.appendf("half result = %s(", lerpFuncName.c_str());
  1151. noiseCode.appendf("%s(%s(%s(%s(AA), p),", lerpFuncName.c_str(), lerpFuncName.c_str(),
  1152. gradFuncName.c_str(), permFuncName.c_str());
  1153. noiseCode.appendf("%s(%s(BA), p + half3(-1.0, 0.0, 0.0)), f.x),", gradFuncName.c_str(),
  1154. permFuncName.c_str());
  1155. noiseCode.appendf("%s(%s(%s(AB), p + half3(0.0, -1.0, 0.0)),", lerpFuncName.c_str(),
  1156. gradFuncName.c_str(), permFuncName.c_str());
  1157. noiseCode.appendf("%s(%s(BB), p + half3(-1.0, -1.0, 0.0)), f.x), f.y),",
  1158. gradFuncName.c_str(), permFuncName.c_str());
  1159. noiseCode.appendf("%s(%s(%s(%s(AA + 1.0), p + half3(0.0, 0.0, -1.0)),",
  1160. lerpFuncName.c_str(), lerpFuncName.c_str(), gradFuncName.c_str(),
  1161. permFuncName.c_str());
  1162. noiseCode.appendf("%s(%s(BA + 1.0), p + half3(-1.0, 0.0, -1.0)), f.x),",
  1163. gradFuncName.c_str(), permFuncName.c_str());
  1164. noiseCode.appendf("%s(%s(%s(AB + 1.0), p + half3(0.0, -1.0, -1.0)),",
  1165. lerpFuncName.c_str(), gradFuncName.c_str(), permFuncName.c_str());
  1166. noiseCode.appendf("%s(%s(BB + 1.0), p + half3(-1.0, -1.0, -1.0)), f.x), f.y), f.z);",
  1167. gradFuncName.c_str(), permFuncName.c_str());
  1168. noiseCode.append("return result;");
  1169. fragBuilder->emitFunction(kHalf_GrSLType, "noise", SK_ARRAY_COUNT(noiseArgs), noiseArgs,
  1170. noiseCode.c_str(), &noiseFuncName);
  1171. // noiseOctaves function
  1172. const GrShaderVar noiseOctavesArgs[] = {
  1173. GrShaderVar("p", kHalf3_GrSLType)
  1174. };
  1175. SkString noiseOctavesFuncName;
  1176. SkString noiseOctavesCode;
  1177. noiseOctavesCode.append("half result = 0.0;");
  1178. noiseOctavesCode.append("half ratio = 1.0;");
  1179. noiseOctavesCode.appendf("for (half i = 0.0; i < %d; i++) {", pne.octaves());
  1180. noiseOctavesCode.appendf("result += %s(p) / ratio;", noiseFuncName.c_str());
  1181. noiseOctavesCode.append("p *= 2.0;");
  1182. noiseOctavesCode.append("ratio *= 2.0;");
  1183. noiseOctavesCode.append("}");
  1184. noiseOctavesCode.append("return (result + 1.0) / 2.0;");
  1185. fragBuilder->emitFunction(kHalf_GrSLType, "noiseOctaves", SK_ARRAY_COUNT(noiseOctavesArgs),
  1186. noiseOctavesArgs, noiseOctavesCode.c_str(), &noiseOctavesFuncName);
  1187. fragBuilder->codeAppendf("half2 coords = half2(%s * %s);", vCoords.c_str(), baseFrequencyUni);
  1188. fragBuilder->codeAppendf("half r = %s(half3(coords, %s));", noiseOctavesFuncName.c_str(),
  1189. zUni);
  1190. fragBuilder->codeAppendf("half g = %s(half3(coords, %s + 0000.0));",
  1191. noiseOctavesFuncName.c_str(), zUni);
  1192. fragBuilder->codeAppendf("half b = %s(half3(coords, %s + 0000.0));",
  1193. noiseOctavesFuncName.c_str(), zUni);
  1194. fragBuilder->codeAppendf("half a = %s(half3(coords, %s + 0000.0));",
  1195. noiseOctavesFuncName.c_str(), zUni);
  1196. fragBuilder->codeAppendf("%s = half4(r, g, b, a);", args.fOutputColor);
  1197. // Clamp values
  1198. fragBuilder->codeAppendf("%s = saturate(%s);", args.fOutputColor, args.fOutputColor);
  1199. // Pre-multiply the result
  1200. fragBuilder->codeAppendf("\n\t\t%s = half4(%s.rgb * %s.aaa, %s.a);\n",
  1201. args.fOutputColor, args.fOutputColor,
  1202. args.fOutputColor, args.fOutputColor);
  1203. }
  1204. void GrGLImprovedPerlinNoise::GenKey(const GrProcessor& processor, const GrShaderCaps&,
  1205. GrProcessorKeyBuilder* b) {
  1206. const GrImprovedPerlinNoiseEffect& pne = processor.cast<GrImprovedPerlinNoiseEffect>();
  1207. b->add32(pne.octaves());
  1208. }
  1209. void GrGLImprovedPerlinNoise::onSetData(const GrGLSLProgramDataManager& pdman,
  1210. const GrFragmentProcessor& processor) {
  1211. INHERITED::onSetData(pdman, processor);
  1212. const GrImprovedPerlinNoiseEffect& noise = processor.cast<GrImprovedPerlinNoiseEffect>();
  1213. const SkVector& baseFrequency = noise.baseFrequency();
  1214. pdman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
  1215. pdman.set1f(fZUni, noise.z());
  1216. }
  1217. /////////////////////////////////////////////////////////////////////
  1218. std::unique_ptr<GrFragmentProcessor> SkPerlinNoiseShaderImpl::asFragmentProcessor(
  1219. const GrFPArgs& args) const {
  1220. SkASSERT(args.fContext);
  1221. const auto localMatrix = this->totalLocalMatrix(args.fPreLocalMatrix, args.fPostLocalMatrix);
  1222. const auto paintMatrix = SkMatrix::Concat(*args.fViewMatrix, *localMatrix);
  1223. // Either we don't stitch tiles, either we have a valid tile size
  1224. SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
  1225. std::unique_ptr<SkPerlinNoiseShaderImpl::PaintingData> paintingData =
  1226. skstd::make_unique<SkPerlinNoiseShaderImpl::PaintingData>(fTileSize,
  1227. fSeed,
  1228. fBaseFrequencyX,
  1229. fBaseFrequencyY,
  1230. paintMatrix);
  1231. SkMatrix m = *args.fViewMatrix;
  1232. m.setTranslateX(-localMatrix->getTranslateX() + SK_Scalar1);
  1233. m.setTranslateY(-localMatrix->getTranslateY() + SK_Scalar1);
  1234. auto proxyProvider = args.fContext->priv().proxyProvider();
  1235. if (fType == kImprovedNoise_Type) {
  1236. // Need to assert that the textures we'll create are power of 2 so a copy isn't needed.
  1237. // We also know that we will not be using mipmaps. If things things weren't true we should
  1238. // go through GrBitmapTextureMaker to handle needed copies.
  1239. const sk_sp<SkImage> permutationsImage = paintingData->getImprovedPermutationsImage();
  1240. SkASSERT(SkIsPow2(permutationsImage->width()) && SkIsPow2(permutationsImage->height()));
  1241. sk_sp<GrTextureProxy> permutationsTexture(
  1242. GrMakeCachedImageProxy(proxyProvider, std::move(permutationsImage)));
  1243. const sk_sp<SkImage> gradientImage = paintingData->getGradientImage();
  1244. SkASSERT(SkIsPow2(gradientImage->width()) && SkIsPow2(gradientImage->height()));
  1245. sk_sp<GrTextureProxy> gradientTexture(
  1246. GrMakeCachedImageProxy(proxyProvider, std::move(gradientImage)));
  1247. return GrImprovedPerlinNoiseEffect::Make(fNumOctaves, fSeed, std::move(paintingData),
  1248. std::move(permutationsTexture),
  1249. std::move(gradientTexture), m);
  1250. }
  1251. if (0 == fNumOctaves) {
  1252. if (kFractalNoise_Type == fType) {
  1253. // Extract the incoming alpha and emit rgba = (a/4, a/4, a/4, a/2)
  1254. // TODO: Either treat the output of this shader as sRGB or allow client to specify a
  1255. // color space of the noise. Either way, this case (and the GLSL) need to convert to
  1256. // the destination.
  1257. auto inner =
  1258. GrConstColorProcessor::Make(SkPMColor4f::FromBytes_RGBA(0x80404040),
  1259. GrConstColorProcessor::InputMode::kModulateRGBA);
  1260. return GrFragmentProcessor::MulChildByInputAlpha(std::move(inner));
  1261. }
  1262. // Emit zero.
  1263. return GrConstColorProcessor::Make(SK_PMColor4fTRANSPARENT,
  1264. GrConstColorProcessor::InputMode::kIgnore);
  1265. }
  1266. // Need to assert that the textures we'll create are power of 2 so that now copy is needed. We
  1267. // also know that we will not be using mipmaps. If things things weren't true we should go
  1268. // through GrBitmapTextureMaker to handle needed copies.
  1269. const sk_sp<SkImage> permutationsImage = paintingData->getPermutationsImage();
  1270. SkASSERT(SkIsPow2(permutationsImage->width()) && SkIsPow2(permutationsImage->height()));
  1271. sk_sp<GrTextureProxy> permutationsProxy = GrMakeCachedImageProxy(proxyProvider,
  1272. std::move(permutationsImage));
  1273. const sk_sp<SkImage> noiseImage = paintingData->getNoiseImage();
  1274. SkASSERT(SkIsPow2(noiseImage->width()) && SkIsPow2(noiseImage->height()));
  1275. sk_sp<GrTextureProxy> noiseProxy = GrMakeCachedImageProxy(proxyProvider,
  1276. std::move(noiseImage));
  1277. if (permutationsProxy && noiseProxy) {
  1278. auto inner = GrPerlinNoise2Effect::Make(fType,
  1279. fNumOctaves,
  1280. fStitchTiles,
  1281. std::move(paintingData),
  1282. std::move(permutationsProxy),
  1283. std::move(noiseProxy),
  1284. m);
  1285. return GrFragmentProcessor::MulChildByInputAlpha(std::move(inner));
  1286. }
  1287. return nullptr;
  1288. }
  1289. #endif
  1290. ///////////////////////////////////////////////////////////////////////////////////////////////////
  1291. static bool valid_input(SkScalar baseX, SkScalar baseY, int numOctaves, const SkISize* tileSize,
  1292. SkScalar seed) {
  1293. if (!(baseX >= 0 && baseY >= 0)) {
  1294. return false;
  1295. }
  1296. if (!(numOctaves >= 0 && numOctaves <= SkPerlinNoiseShaderImpl::kMaxOctaves)) {
  1297. return false;
  1298. }
  1299. if (tileSize && !(tileSize->width() >= 0 && tileSize->height() >= 0)) {
  1300. return false;
  1301. }
  1302. if (!SkScalarIsFinite(seed)) {
  1303. return false;
  1304. }
  1305. return true;
  1306. }
  1307. sk_sp<SkShader> SkPerlinNoiseShader::MakeFractalNoise(SkScalar baseFrequencyX,
  1308. SkScalar baseFrequencyY,
  1309. int numOctaves, SkScalar seed,
  1310. const SkISize* tileSize) {
  1311. if (!valid_input(baseFrequencyX, baseFrequencyY, numOctaves, tileSize, seed)) {
  1312. return nullptr;
  1313. }
  1314. return sk_sp<SkShader>(new SkPerlinNoiseShaderImpl(SkPerlinNoiseShaderImpl::kFractalNoise_Type,
  1315. baseFrequencyX, baseFrequencyY, numOctaves, seed,
  1316. tileSize));
  1317. }
  1318. sk_sp<SkShader> SkPerlinNoiseShader::MakeTurbulence(SkScalar baseFrequencyX,
  1319. SkScalar baseFrequencyY,
  1320. int numOctaves, SkScalar seed,
  1321. const SkISize* tileSize) {
  1322. if (!valid_input(baseFrequencyX, baseFrequencyY, numOctaves, tileSize, seed)) {
  1323. return nullptr;
  1324. }
  1325. return sk_sp<SkShader>(new SkPerlinNoiseShaderImpl(SkPerlinNoiseShaderImpl::kTurbulence_Type,
  1326. baseFrequencyX, baseFrequencyY, numOctaves, seed,
  1327. tileSize));
  1328. }
  1329. sk_sp<SkShader> SkPerlinNoiseShader::MakeImprovedNoise(SkScalar baseFrequencyX,
  1330. SkScalar baseFrequencyY,
  1331. int numOctaves, SkScalar z) {
  1332. if (!valid_input(baseFrequencyX, baseFrequencyY, numOctaves, nullptr, z)) {
  1333. return nullptr;
  1334. }
  1335. return sk_sp<SkShader>(new SkPerlinNoiseShaderImpl(SkPerlinNoiseShaderImpl::kImprovedNoise_Type,
  1336. baseFrequencyX, baseFrequencyY, numOctaves, z,
  1337. nullptr));
  1338. }
  1339. void SkPerlinNoiseShader::RegisterFlattenables() {
  1340. SK_REGISTER_FLATTENABLE(SkPerlinNoiseShaderImpl);
  1341. }