blob: ed63fafae14c14093c5f66c21f482c9011ffa482 [file] [log] [blame]
sugoi@google.come3b4c502013-04-05 13:47:09 +00001/*
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
8#include "SkDither.h"
9#include "SkPerlinNoiseShader.h"
commit-bot@chromium.orgc2a0ea62013-11-06 10:08:38 +000010#include "SkColorFilter.h"
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +000011#include "SkReadBuffer.h"
12#include "SkWriteBuffer.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000013#include "SkShader.h"
14#include "SkUnPreMultiply.h"
15#include "SkString.h"
16
17#if SK_SUPPORT_GPU
18#include "GrContext.h"
bsalomon@google.com77af6802013-10-02 13:04:56 +000019#include "GrCoordTransform.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000020#include "gl/GrGLEffect.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000021#include "GrTBackendEffectFactory.h"
22#include "SkGr.h"
23#endif
24
25static const int kBlockSize = 256;
26static const int kBlockMask = kBlockSize - 1;
27static const int kPerlinNoise = 4096;
28static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
29
30namespace {
31
32// noiseValue is the color component's value (or color)
33// limitValue is the maximum perlin noise array index value allowed
34// newValue is the current noise dimension (either width or height)
35inline int checkNoise(int noiseValue, int limitValue, int newValue) {
36 // If the noise value would bring us out of bounds of the current noise array while we are
37 // stiching noise tiles together, wrap the noise around the current dimension of the noise to
38 // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
39 if (noiseValue >= limitValue) {
40 noiseValue -= newValue;
41 }
42 if (noiseValue >= limitValue - 1) {
43 noiseValue -= newValue - 1;
44 }
45 return noiseValue;
46}
47
48inline SkScalar smoothCurve(SkScalar t) {
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +000049 static const SkScalar SK_Scalar3 = 3.0f;
sugoi@google.come3b4c502013-04-05 13:47:09 +000050
51 // returns t * t * (3 - 2 * t)
52 return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
53}
54
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +000055bool perlin_noise_type_is_valid(SkPerlinNoiseShader::Type type) {
56 return (SkPerlinNoiseShader::kFractalNoise_Type == type) ||
57 (SkPerlinNoiseShader::kTurbulence_Type == type);
58}
59
sugoi@google.come3b4c502013-04-05 13:47:09 +000060} // end namespace
61
62struct SkPerlinNoiseShader::StitchData {
63 StitchData()
64 : fWidth(0)
65 , fWrapX(0)
66 , fHeight(0)
67 , fWrapY(0)
68 {}
69
70 bool operator==(const StitchData& other) const {
71 return fWidth == other.fWidth &&
72 fWrapX == other.fWrapX &&
73 fHeight == other.fHeight &&
74 fWrapY == other.fWrapY;
75 }
76
77 int fWidth; // How much to subtract to wrap for stitching.
78 int fWrapX; // Minimum value to wrap.
79 int fHeight;
80 int fWrapY;
81};
82
83struct SkPerlinNoiseShader::PaintingData {
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +000084 PaintingData(const SkISize& tileSize, SkScalar seed,
85 SkScalar baseFrequencyX, SkScalar baseFrequencyY)
86 : fTileSize(tileSize)
87 , fBaseFrequency(SkPoint::Make(baseFrequencyX, baseFrequencyY))
sugoi@google.come3b4c502013-04-05 13:47:09 +000088 {
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +000089 this->init(seed);
90 if (!fTileSize.isEmpty()) {
91 this->stitch();
92 }
93
94#if SK_SUPPORT_GPU && !defined(SK_USE_SIMPLEX_NOISE)
95 fPermutationsBitmap.setConfig(SkImageInfo::MakeA8(kBlockSize, 1));
96 fPermutationsBitmap.setPixels(fLatticeSelector);
97
98 fNoiseBitmap.setConfig(SkImageInfo::MakeN32Premul(kBlockSize, 4));
99 fNoiseBitmap.setPixels(fNoise[0][0]);
100#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +0000101 }
102
103 int fSeed;
104 uint8_t fLatticeSelector[kBlockSize];
105 uint16_t fNoise[4][kBlockSize][2];
106 SkPoint fGradient[4][kBlockSize];
107 SkISize fTileSize;
108 SkVector fBaseFrequency;
109 StitchData fStitchDataInit;
110
111private:
112
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000113#if SK_SUPPORT_GPU && !defined(SK_USE_SIMPLEX_NOISE)
114 SkBitmap fPermutationsBitmap;
115 SkBitmap fNoiseBitmap;
116#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +0000117
118 inline int random() {
119 static const int gRandAmplitude = 16807; // 7**5; primitive root of m
120 static const int gRandQ = 127773; // m / a
121 static const int gRandR = 2836; // m % a
122
123 int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
124 if (result <= 0)
125 result += kRandMaximum;
126 fSeed = result;
127 return result;
128 }
129
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000130 // Only called once. Could be part of the constructor.
sugoi@google.come3b4c502013-04-05 13:47:09 +0000131 void init(SkScalar seed)
132 {
133 static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
134
senorblanco@chromium.org857e3202014-01-09 17:41:42 +0000135 // According to the SVG spec, we must truncate (not round) the seed value.
136 fSeed = SkScalarTruncToInt(seed);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000137 // The seed value clamp to the range [1, kRandMaximum - 1].
sugoi@google.come3b4c502013-04-05 13:47:09 +0000138 if (fSeed <= 0) {
139 fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
140 }
141 if (fSeed > kRandMaximum - 1) {
142 fSeed = kRandMaximum - 1;
143 }
144 for (int channel = 0; channel < 4; ++channel) {
145 for (int i = 0; i < kBlockSize; ++i) {
146 fLatticeSelector[i] = i;
147 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
148 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
149 }
150 }
151 for (int i = kBlockSize - 1; i > 0; --i) {
152 int k = fLatticeSelector[i];
153 int j = random() % kBlockSize;
154 SkASSERT(j >= 0);
155 SkASSERT(j < kBlockSize);
156 fLatticeSelector[i] = fLatticeSelector[j];
157 fLatticeSelector[j] = k;
158 }
159
160 // Perform the permutations now
161 {
162 // Copy noise data
163 uint16_t noise[4][kBlockSize][2];
164 for (int i = 0; i < kBlockSize; ++i) {
165 for (int channel = 0; channel < 4; ++channel) {
166 for (int j = 0; j < 2; ++j) {
167 noise[channel][i][j] = fNoise[channel][i][j];
168 }
169 }
170 }
171 // Do permutations on noise data
172 for (int i = 0; i < kBlockSize; ++i) {
173 for (int channel = 0; channel < 4; ++channel) {
174 for (int j = 0; j < 2; ++j) {
175 fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
176 }
177 }
178 }
179 }
180
181 // Half of the largest possible value for 16 bit unsigned int
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +0000182 static const SkScalar gHalfMax16bits = 32767.5f;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000183
184 // Compute gradients from permutated noise data
185 for (int channel = 0; channel < 4; ++channel) {
186 for (int i = 0; i < kBlockSize; ++i) {
187 fGradient[channel][i] = SkPoint::Make(
188 SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
189 gInvBlockSizef),
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000190 SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
sugoi@google.come3b4c502013-04-05 13:47:09 +0000191 gInvBlockSizef));
192 fGradient[channel][i].normalize();
193 // Put the normalized gradient back into the noise data
194 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000195 fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000196 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000197 fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000198 }
199 }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000200 }
201
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000202 // Only called once. Could be part of the constructor.
sugoi@google.come3b4c502013-04-05 13:47:09 +0000203 void stitch() {
204 SkScalar tileWidth = SkIntToScalar(fTileSize.width());
205 SkScalar tileHeight = SkIntToScalar(fTileSize.height());
206 SkASSERT(tileWidth > 0 && tileHeight > 0);
207 // When stitching tiled turbulence, the frequencies must be adjusted
208 // so that the tile borders will be continuous.
209 if (fBaseFrequency.fX) {
reed@google.com8015cdd2013-12-18 15:49:32 +0000210 SkScalar lowFrequencx =
211 SkScalarFloorToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
212 SkScalar highFrequencx =
213 SkScalarCeilToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000214 // BaseFrequency should be non-negative according to the standard.
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000215 if (SkScalarDiv(fBaseFrequency.fX, lowFrequencx) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000216 SkScalarDiv(highFrequencx, fBaseFrequency.fX)) {
217 fBaseFrequency.fX = lowFrequencx;
218 } else {
219 fBaseFrequency.fX = highFrequencx;
220 }
221 }
222 if (fBaseFrequency.fY) {
reed@google.com8015cdd2013-12-18 15:49:32 +0000223 SkScalar lowFrequency =
224 SkScalarFloorToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
225 SkScalar highFrequency =
226 SkScalarCeilToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000227 if (SkScalarDiv(fBaseFrequency.fY, lowFrequency) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000228 SkScalarDiv(highFrequency, fBaseFrequency.fY)) {
229 fBaseFrequency.fY = lowFrequency;
230 } else {
231 fBaseFrequency.fY = highFrequency;
232 }
233 }
234 // Set up TurbulenceInitial stitch values.
235 fStitchDataInit.fWidth =
reed@google.com8015cdd2013-12-18 15:49:32 +0000236 SkScalarRoundToInt(tileWidth * fBaseFrequency.fX);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000237 fStitchDataInit.fWrapX = kPerlinNoise + fStitchDataInit.fWidth;
238 fStitchDataInit.fHeight =
reed@google.com8015cdd2013-12-18 15:49:32 +0000239 SkScalarRoundToInt(tileHeight * fBaseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000240 fStitchDataInit.fWrapY = kPerlinNoise + fStitchDataInit.fHeight;
241 }
242
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000243public:
sugoi@google.come3b4c502013-04-05 13:47:09 +0000244
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000245#if SK_SUPPORT_GPU && !defined(SK_USE_SIMPLEX_NOISE)
246 const SkBitmap& getPermutationsBitmap() const { return fPermutationsBitmap; }
247
248 const SkBitmap& getNoiseBitmap() const { return fNoiseBitmap; }
249#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +0000250};
251
252SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
253 int numOctaves, SkScalar seed,
254 const SkISize* tileSize) {
255 return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY,
256 numOctaves, seed, tileSize));
257}
258
commit-bot@chromium.org9fbbcca2014-04-01 16:09:37 +0000259SkShader* SkPerlinNoiseShader::CreateTurbulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000260 int numOctaves, SkScalar seed,
261 const SkISize* tileSize) {
262 return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY,
263 numOctaves, seed, tileSize));
264}
265
266SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
267 SkScalar baseFrequencyX,
268 SkScalar baseFrequencyY,
269 int numOctaves,
270 SkScalar seed,
271 const SkISize* tileSize)
272 : fType(type)
273 , fBaseFrequencyX(baseFrequencyX)
274 , fBaseFrequencyY(baseFrequencyY)
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +0000275 , fNumOctaves(numOctaves > 255 ? 255 : numOctaves/*[0,255] octaves allowed*/)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000276 , fSeed(seed)
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000277 , fTileSize(NULL == tileSize ? SkISize::Make(0, 0) : *tileSize)
278 , fStitchTiles(!fTileSize.isEmpty())
sugoi@google.come3b4c502013-04-05 13:47:09 +0000279{
280 SkASSERT(numOctaves >= 0 && numOctaves < 256);
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000281 fMatrix.reset();
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000282 fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize, fSeed, fBaseFrequencyX, fBaseFrequencyY));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000283}
284
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000285SkPerlinNoiseShader::SkPerlinNoiseShader(SkReadBuffer& buffer)
286 : INHERITED(buffer)
287{
sugoi@google.come3b4c502013-04-05 13:47:09 +0000288 fType = (SkPerlinNoiseShader::Type) buffer.readInt();
289 fBaseFrequencyX = buffer.readScalar();
290 fBaseFrequencyY = buffer.readScalar();
291 fNumOctaves = buffer.readInt();
292 fSeed = buffer.readScalar();
293 fStitchTiles = buffer.readBool();
294 fTileSize.fWidth = buffer.readInt();
295 fTileSize.fHeight = buffer.readInt();
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000296 fMatrix.reset();
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000297 fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize, fSeed, fBaseFrequencyX, fBaseFrequencyY));
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +0000298 buffer.validate(perlin_noise_type_is_valid(fType) &&
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +0000299 (fNumOctaves >= 0) && (fNumOctaves <= 255) &&
300 (fStitchTiles != fTileSize.isEmpty()));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000301}
302
303SkPerlinNoiseShader::~SkPerlinNoiseShader() {
304 // Safety, should have been done in endContext()
305 SkDELETE(fPaintingData);
306}
307
commit-bot@chromium.org8b0e8ac2014-01-30 18:58:24 +0000308void SkPerlinNoiseShader::flatten(SkWriteBuffer& buffer) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000309 this->INHERITED::flatten(buffer);
310 buffer.writeInt((int) fType);
311 buffer.writeScalar(fBaseFrequencyX);
312 buffer.writeScalar(fBaseFrequencyY);
313 buffer.writeInt(fNumOctaves);
314 buffer.writeScalar(fSeed);
315 buffer.writeBool(fStitchTiles);
316 buffer.writeInt(fTileSize.fWidth);
317 buffer.writeInt(fTileSize.fHeight);
318}
319
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000320SkScalar SkPerlinNoiseShader::noise2D(int channel, const PaintingData& paintingData,
321 const StitchData& stitchData,
322 const SkPoint& noiseVector) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000323 struct Noise {
324 int noisePositionIntegerValue;
325 SkScalar noisePositionFractionValue;
326 Noise(SkScalar component)
327 {
328 SkScalar position = component + kPerlinNoise;
329 noisePositionIntegerValue = SkScalarFloorToInt(position);
330 noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
331 }
332 };
333 Noise noiseX(noiseVector.x());
334 Noise noiseY(noiseVector.y());
335 SkScalar u, v;
336 // If stitching, adjust lattice points accordingly.
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000337 if (fStitchTiles) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000338 noiseX.noisePositionIntegerValue =
339 checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
340 noiseY.noisePositionIntegerValue =
341 checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
342 }
343 noiseX.noisePositionIntegerValue &= kBlockMask;
344 noiseY.noisePositionIntegerValue &= kBlockMask;
345 int latticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000346 paintingData.fLatticeSelector[noiseX.noisePositionIntegerValue] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000347 noiseY.noisePositionIntegerValue;
348 int nextLatticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000349 paintingData.fLatticeSelector[(noiseX.noisePositionIntegerValue + 1) & kBlockMask] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000350 noiseY.noisePositionIntegerValue;
351 SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
352 SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
353 // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
354 SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
355 noiseY.noisePositionFractionValue); // Offset (0,0)
356 u = paintingData.fGradient[channel][latticeIndex & kBlockMask].dot(fractionValue);
357 fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
358 v = paintingData.fGradient[channel][nextLatticeIndex & kBlockMask].dot(fractionValue);
359 SkScalar a = SkScalarInterp(u, v, sx);
360 fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
361 v = paintingData.fGradient[channel][(nextLatticeIndex + 1) & kBlockMask].dot(fractionValue);
362 fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
363 u = paintingData.fGradient[channel][(latticeIndex + 1) & kBlockMask].dot(fractionValue);
364 SkScalar b = SkScalarInterp(u, v, sx);
365 return SkScalarInterp(a, b, sy);
366}
367
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000368SkScalar SkPerlinNoiseShader::calculateTurbulenceValueForPoint(int channel,
369 const PaintingData& paintingData,
370 StitchData& stitchData,
371 const SkPoint& point) const {
372 if (fStitchTiles) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000373 // Set up TurbulenceInitial stitch values.
374 stitchData = paintingData.fStitchDataInit;
375 }
376 SkScalar turbulenceFunctionResult = 0;
377 SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), paintingData.fBaseFrequency.fX),
378 SkScalarMul(point.y(), paintingData.fBaseFrequency.fY)));
379 SkScalar ratio = SK_Scalar1;
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000380 for (int octave = 0; octave < fNumOctaves; ++octave) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000381 SkScalar noise = noise2D(channel, paintingData, stitchData, noiseVector);
382 turbulenceFunctionResult += SkScalarDiv(
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000383 (fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000384 noiseVector.fX *= 2;
385 noiseVector.fY *= 2;
386 ratio *= 2;
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000387 if (fStitchTiles) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000388 // Update stitch values
389 stitchData.fWidth *= 2;
390 stitchData.fWrapX = stitchData.fWidth + kPerlinNoise;
391 stitchData.fHeight *= 2;
392 stitchData.fWrapY = stitchData.fHeight + kPerlinNoise;
393 }
394 }
395
396 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
397 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000398 if (fType == kFractalNoise_Type) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000399 turbulenceFunctionResult =
400 SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
401 }
402
403 if (channel == 3) { // Scale alpha by paint value
404 turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult,
405 SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255)));
406 }
407
408 // Clamp result
409 return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
410}
411
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000412SkPMColor SkPerlinNoiseShader::shade(const SkPoint& point, StitchData& stitchData) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000413 SkPoint newPoint;
senorblanco@chromium.orga8d95f82014-04-04 14:46:10 +0000414 fMatrix.mapPoints(&newPoint, &point, 1);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000415 newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
416 newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
417
418 U8CPU rgba[4];
419 for (int channel = 3; channel >= 0; --channel) {
420 rgba[channel] = SkScalarFloorToInt(255 *
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000421 calculateTurbulenceValueForPoint(channel, *fPaintingData, stitchData, newPoint));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000422 }
423 return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
424}
425
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000426bool SkPerlinNoiseShader::setContext(const SkBitmap& device, const SkPaint& paint,
427 const SkMatrix& matrix) {
senorblanco@chromium.orga8d95f82014-04-04 14:46:10 +0000428 SkMatrix newMatrix = matrix;
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000429 newMatrix.postConcat(getLocalMatrix());
senorblanco@chromium.orga8d95f82014-04-04 14:46:10 +0000430 SkMatrix invMatrix;
431 if (!newMatrix.invert(&invMatrix)) {
432 invMatrix.reset();
433 }
434 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
435 // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
436 newMatrix.postTranslate(SK_Scalar1, SK_Scalar1);
437 newMatrix.postConcat(invMatrix);
438 newMatrix.postConcat(invMatrix);
439 fMatrix = newMatrix;
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000440 return INHERITED::setContext(device, paint, matrix);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000441}
442
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000443void SkPerlinNoiseShader::shadeSpan(int x, int y, SkPMColor result[], int count) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000444 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
445 StitchData stitchData;
446 for (int i = 0; i < count; ++i) {
447 result[i] = shade(point, stitchData);
448 point.fX += SK_Scalar1;
449 }
450}
451
commit-bot@chromium.org6e5671d2014-04-23 16:16:55 +0000452void SkPerlinNoiseShader::shadeSpan16(int x, int y, uint16_t result[], int count) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000453 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
454 StitchData stitchData;
455 DITHER_565_SCAN(y);
456 for (int i = 0; i < count; ++i) {
457 unsigned dither = DITHER_VALUE(x);
458 result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
459 DITHER_INC_X(x);
460 point.fX += SK_Scalar1;
461 }
462}
463
464/////////////////////////////////////////////////////////////////////
465
commit-bot@chromium.org344cf452013-06-17 14:19:01 +0000466#if SK_SUPPORT_GPU
sugoi@google.come3b4c502013-04-05 13:47:09 +0000467
468#include "GrTBackendEffectFactory.h"
469
sugoi@google.com4775cba2013-04-17 13:46:56 +0000470class GrGLNoise : public GrGLEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000471public:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000472 GrGLNoise(const GrBackendEffectFactory& factory,
473 const GrDrawEffect& drawEffect);
474 virtual ~GrGLNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000475
sugoi@google.com4775cba2013-04-17 13:46:56 +0000476 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
477
478 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
479
480protected:
481 SkPerlinNoiseShader::Type fType;
482 bool fStitchTiles;
483 int fNumOctaves;
484 GrGLUniformManager::UniformHandle fBaseFrequencyUni;
485 GrGLUniformManager::UniformHandle fAlphaUni;
486 GrGLUniformManager::UniformHandle fInvMatrixUni;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000487
488private:
489 typedef GrGLEffect INHERITED;
490};
491
492class GrGLPerlinNoise : public GrGLNoise {
493public:
sugoi@google.come3b4c502013-04-05 13:47:09 +0000494 GrGLPerlinNoise(const GrBackendEffectFactory& factory,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000495 const GrDrawEffect& drawEffect)
496 : GrGLNoise(factory, drawEffect) {}
497 virtual ~GrGLPerlinNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000498
499 virtual void emitCode(GrGLShaderBuilder*,
500 const GrDrawEffect&,
501 EffectKey,
502 const char* outputColor,
503 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000504 const TransformedCoordsArray&,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000505 const TextureSamplerArray&) SK_OVERRIDE;
506
sugoi@google.com4775cba2013-04-17 13:46:56 +0000507 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000508
509private:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000510 GrGLUniformManager::UniformHandle fStitchDataUni;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000511
sugoi@google.com4775cba2013-04-17 13:46:56 +0000512 typedef GrGLNoise INHERITED;
513};
514
515class GrGLSimplexNoise : public GrGLNoise {
516 // Note : This is for reference only. GrGLPerlinNoise is used for processing.
517public:
518 GrGLSimplexNoise(const GrBackendEffectFactory& factory,
519 const GrDrawEffect& drawEffect)
520 : GrGLNoise(factory, drawEffect) {}
521
522 virtual ~GrGLSimplexNoise() {}
523
524 virtual void emitCode(GrGLShaderBuilder*,
525 const GrDrawEffect&,
526 EffectKey,
527 const char* outputColor,
528 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000529 const TransformedCoordsArray&,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000530 const TextureSamplerArray&) SK_OVERRIDE;
531
532 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
533
534private:
535 GrGLUniformManager::UniformHandle fSeedUni;
536
537 typedef GrGLNoise INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000538};
539
540/////////////////////////////////////////////////////////////////////
541
sugoi@google.com4775cba2013-04-17 13:46:56 +0000542class GrNoiseEffect : public GrEffect {
543public:
544 virtual ~GrNoiseEffect() { }
545
546 SkPerlinNoiseShader::Type type() const { return fType; }
547 bool stitchTiles() const { return fStitchTiles; }
548 const SkVector& baseFrequency() const { return fBaseFrequency; }
549 int numOctaves() const { return fNumOctaves; }
bsalomon@google.com77af6802013-10-02 13:04:56 +0000550 const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000551 uint8_t alpha() const { return fAlpha; }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000552
553 void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE {
554 *validFlags = 0; // This is noise. Nothing is constant.
555 }
556
557protected:
558 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
559 const GrNoiseEffect& s = CastEffect<GrNoiseEffect>(sBase);
560 return fType == s.fType &&
561 fBaseFrequency == s.fBaseFrequency &&
562 fNumOctaves == s.fNumOctaves &&
563 fStitchTiles == s.fStitchTiles &&
bsalomon@google.com77af6802013-10-02 13:04:56 +0000564 fCoordTransform.getMatrix() == s.fCoordTransform.getMatrix() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000565 fAlpha == s.fAlpha;
566 }
567
568 GrNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, int numOctaves,
569 bool stitchTiles, const SkMatrix& matrix, uint8_t alpha)
570 : fType(type)
571 , fBaseFrequency(baseFrequency)
572 , fNumOctaves(numOctaves)
573 , fStitchTiles(stitchTiles)
574 , fMatrix(matrix)
575 , fAlpha(alpha) {
bsalomon@google.com77af6802013-10-02 13:04:56 +0000576 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
577 // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions.
578 SkMatrix m = matrix;
579 m.postTranslate(SK_Scalar1, SK_Scalar1);
580 fCoordTransform.reset(kLocal_GrCoordSet, m);
581 this->addCoordTransform(&fCoordTransform);
commit-bot@chromium.orga34995e2013-10-23 05:42:03 +0000582 this->setWillNotUseInputColor();
sugoi@google.com4775cba2013-04-17 13:46:56 +0000583 }
584
585 SkPerlinNoiseShader::Type fType;
bsalomon@google.com77af6802013-10-02 13:04:56 +0000586 GrCoordTransform fCoordTransform;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000587 SkVector fBaseFrequency;
588 int fNumOctaves;
589 bool fStitchTiles;
590 SkMatrix fMatrix;
591 uint8_t fAlpha;
592
593private:
594 typedef GrEffect INHERITED;
595};
596
597class GrPerlinNoiseEffect : public GrNoiseEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000598public:
599 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
600 int numOctaves, bool stitchTiles,
601 const SkPerlinNoiseShader::StitchData& stitchData,
602 GrTexture* permutationsTexture, GrTexture* noiseTexture,
603 const SkMatrix& matrix, uint8_t alpha) {
604 AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves,
605 stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha)));
606 return CreateEffectRef(effect);
607 }
608
609 virtual ~GrPerlinNoiseEffect() { }
610
611 static const char* Name() { return "PerlinNoise"; }
612 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
613 return GrTBackendEffectFactory<GrPerlinNoiseEffect>::getInstance();
614 }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000615 const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000616
617 typedef GrGLPerlinNoise GLEffect;
618
sugoi@google.come3b4c502013-04-05 13:47:09 +0000619private:
620 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
621 const GrPerlinNoiseEffect& s = CastEffect<GrPerlinNoiseEffect>(sBase);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000622 return INHERITED::onIsEqual(sBase) &&
623 fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() &&
sugoi@google.come3b4c502013-04-05 13:47:09 +0000624 fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000625 fStitchData == s.fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000626 }
627
628 GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
629 int numOctaves, bool stitchTiles,
630 const SkPerlinNoiseShader::StitchData& stitchData,
631 GrTexture* permutationsTexture, GrTexture* noiseTexture,
632 const SkMatrix& matrix, uint8_t alpha)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000633 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
634 , fPermutationsAccess(permutationsTexture)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000635 , fNoiseAccess(noiseTexture)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000636 , fStitchData(stitchData) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000637 this->addTextureAccess(&fPermutationsAccess);
638 this->addTextureAccess(&fNoiseAccess);
639 }
640
sugoi@google.com4775cba2013-04-17 13:46:56 +0000641 GR_DECLARE_EFFECT_TEST;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000642
643 GrTextureAccess fPermutationsAccess;
644 GrTextureAccess fNoiseAccess;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000645 SkPerlinNoiseShader::StitchData fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000646
sugoi@google.com4775cba2013-04-17 13:46:56 +0000647 typedef GrNoiseEffect INHERITED;
648};
649
650class GrSimplexNoiseEffect : public GrNoiseEffect {
651 // Note : This is for reference only. GrPerlinNoiseEffect is used for processing.
652public:
653 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
654 int numOctaves, bool stitchTiles, const SkScalar seed,
655 const SkMatrix& matrix, uint8_t alpha) {
656 AutoEffectUnref effect(SkNEW_ARGS(GrSimplexNoiseEffect, (type, baseFrequency, numOctaves,
657 stitchTiles, seed, matrix, alpha)));
658 return CreateEffectRef(effect);
659 }
660
661 virtual ~GrSimplexNoiseEffect() { }
662
663 static const char* Name() { return "SimplexNoise"; }
664 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
665 return GrTBackendEffectFactory<GrSimplexNoiseEffect>::getInstance();
666 }
667 const SkScalar& seed() const { return fSeed; }
668
669 typedef GrGLSimplexNoise GLEffect;
670
671private:
672 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
673 const GrSimplexNoiseEffect& s = CastEffect<GrSimplexNoiseEffect>(sBase);
674 return INHERITED::onIsEqual(sBase) && fSeed == s.fSeed;
675 }
676
677 GrSimplexNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
678 int numOctaves, bool stitchTiles, const SkScalar seed,
679 const SkMatrix& matrix, uint8_t alpha)
680 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
681 , fSeed(seed) {
682 }
683
684 SkScalar fSeed;
685
686 typedef GrNoiseEffect INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000687};
688
689/////////////////////////////////////////////////////////////////////
sugoi@google.come3b4c502013-04-05 13:47:09 +0000690GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect);
691
commit-bot@chromium.orge0e7cfe2013-09-09 20:09:12 +0000692GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkRandom* random,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000693 GrContext* context,
694 const GrDrawTargetCaps&,
695 GrTexture**) {
sugoi@google.com423ac132013-04-18 14:04:57 +0000696 int numOctaves = random->nextRangeU(2, 10);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000697 bool stitchTiles = random->nextBool();
698 SkScalar seed = SkIntToScalar(random->nextU());
699 SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +0000700 SkScalar baseFrequencyX = random->nextRangeScalar(0.01f,
701 0.99f);
702 SkScalar baseFrequencyY = random->nextRangeScalar(0.01f,
703 0.99f);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000704
705 SkShader* shader = random->nextBool() ?
706 SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
707 stitchTiles ? &tileSize : NULL) :
commit-bot@chromium.org9fbbcca2014-04-01 16:09:37 +0000708 SkPerlinNoiseShader::CreateTurbulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000709 stitchTiles ? &tileSize : NULL);
710
711 SkPaint paint;
712 GrEffectRef* effect = shader->asNewEffect(context, paint);
713
714 SkDELETE(shader);
715
716 return effect;
717}
sugoi@google.com4775cba2013-04-17 13:46:56 +0000718
sugoi@google.come3b4c502013-04-05 13:47:09 +0000719/////////////////////////////////////////////////////////////////////
720
sugoi@google.com4775cba2013-04-17 13:46:56 +0000721void GrGLSimplexNoise::emitCode(GrGLShaderBuilder* builder,
722 const GrDrawEffect&,
723 EffectKey key,
724 const char* outputColor,
725 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000726 const TransformedCoordsArray& coords,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000727 const TextureSamplerArray&) {
728 sk_ignore_unused_variable(inputColor);
729
bsalomon@google.com77af6802013-10-02 13:04:56 +0000730 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000731
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000732 fSeedUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000733 kFloat_GrSLType, "seed");
734 const char* seedUni = builder->getUniformCStr(fSeedUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000735 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000736 kMat33f_GrSLType, "invMatrix");
737 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000738 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000739 kVec2f_GrSLType, "baseFrequency");
740 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000741 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000742 kFloat_GrSLType, "alpha");
743 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
744
745 // Add vec3 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000746 static const GrGLShaderVar gVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000747 GrGLShaderVar("x", kVec3f_GrSLType)
748 };
749
750 SkString mod289_3_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000751 builder->fsEmitFunction(kVec3f_GrSLType,
752 "mod289", SK_ARRAY_COUNT(gVec3Args), gVec3Args,
753 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
754 "return x - floor(x * C.xxx) * C.yyy;", &mod289_3_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000755
756 // Add vec4 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000757 static const GrGLShaderVar gVec4Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000758 GrGLShaderVar("x", kVec4f_GrSLType)
759 };
760
761 SkString mod289_4_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000762 builder->fsEmitFunction(kVec4f_GrSLType,
763 "mod289", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
764 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
765 "return x - floor(x * C.xxxx) * C.yyyy;", &mod289_4_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000766
767 // Add vec4 permute function
sugoi@google.comd537af52013-06-10 13:59:25 +0000768 SkString permuteCode;
769 permuteCode.appendf("const vec2 C = vec2(34.0, 1.0);\n"
770 "return %s(((x * C.xxxx) + C.yyyy) * x);", mod289_4_funcName.c_str());
771 SkString permuteFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000772 builder->fsEmitFunction(kVec4f_GrSLType,
773 "permute", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
774 permuteCode.c_str(), &permuteFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000775
776 // Add vec4 taylorInvSqrt function
sugoi@google.comd537af52013-06-10 13:59:25 +0000777 SkString taylorInvSqrtFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000778 builder->fsEmitFunction(kVec4f_GrSLType,
779 "taylorInvSqrt", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
780 "const vec2 C = vec2(-0.85373472095314, 1.79284291400159);\n"
781 "return x * C.xxxx + C.yyyy;", &taylorInvSqrtFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000782
783 // Add vec3 noise function
sugoi@google.comd537af52013-06-10 13:59:25 +0000784 static const GrGLShaderVar gNoiseVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000785 GrGLShaderVar("v", kVec3f_GrSLType)
786 };
787
sugoi@google.comd537af52013-06-10 13:59:25 +0000788 SkString noiseCode;
789 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000790 "const vec2 C = vec2(1.0/6.0, 1.0/3.0);\n"
791 "const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n"
792
793 // First corner
794 "vec3 i = floor(v + dot(v, C.yyy));\n"
795 "vec3 x0 = v - i + dot(i, C.xxx);\n"
796
797 // Other corners
798 "vec3 g = step(x0.yzx, x0.xyz);\n"
799 "vec3 l = 1.0 - g;\n"
800 "vec3 i1 = min(g.xyz, l.zxy);\n"
801 "vec3 i2 = max(g.xyz, l.zxy);\n"
802
803 "vec3 x1 = x0 - i1 + C.xxx;\n"
804 "vec3 x2 = x0 - i2 + C.yyy;\n" // 2.0*C.x = 1/3 = C.y
805 "vec3 x3 = x0 - D.yyy;\n" // -1.0+3.0*C.x = -0.5 = -D.y
806 );
807
sugoi@google.comd537af52013-06-10 13:59:25 +0000808 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000809 // Permutations
810 "i = %s(i);\n"
811 "vec4 p = %s(%s(%s(\n"
812 " i.z + vec4(0.0, i1.z, i2.z, 1.0)) +\n"
813 " i.y + vec4(0.0, i1.y, i2.y, 1.0)) +\n"
814 " i.x + vec4(0.0, i1.x, i2.x, 1.0));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000815 mod289_3_funcName.c_str(), permuteFuncName.c_str(), permuteFuncName.c_str(),
816 permuteFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000817
sugoi@google.comd537af52013-06-10 13:59:25 +0000818 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000819 // Gradients: 7x7 points over a square, mapped onto an octahedron.
820 // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
821 "float n_ = 0.142857142857;\n" // 1.0/7.0
822 "vec3 ns = n_ * D.wyz - D.xzx;\n"
823
824 "vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\n" // mod(p,7*7)
825
826 "vec4 x_ = floor(j * ns.z);\n"
827 "vec4 y_ = floor(j - 7.0 * x_);" // mod(j,N)
828
829 "vec4 x = x_ *ns.x + ns.yyyy;\n"
830 "vec4 y = y_ *ns.x + ns.yyyy;\n"
831 "vec4 h = 1.0 - abs(x) - abs(y);\n"
832
833 "vec4 b0 = vec4(x.xy, y.xy);\n"
834 "vec4 b1 = vec4(x.zw, y.zw);\n"
835 );
836
sugoi@google.comd537af52013-06-10 13:59:25 +0000837 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000838 "vec4 s0 = floor(b0) * 2.0 + 1.0;\n"
839 "vec4 s1 = floor(b1) * 2.0 + 1.0;\n"
840 "vec4 sh = -step(h, vec4(0.0));\n"
841
842 "vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;\n"
843 "vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;\n"
844
845 "vec3 p0 = vec3(a0.xy, h.x);\n"
846 "vec3 p1 = vec3(a0.zw, h.y);\n"
847 "vec3 p2 = vec3(a1.xy, h.z);\n"
848 "vec3 p3 = vec3(a1.zw, h.w);\n"
849 );
850
sugoi@google.comd537af52013-06-10 13:59:25 +0000851 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000852 // Normalise gradients
853 "vec4 norm = %s(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n"
854 "p0 *= norm.x;\n"
855 "p1 *= norm.y;\n"
856 "p2 *= norm.z;\n"
857 "p3 *= norm.w;\n"
858
859 // Mix final noise value
860 "vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n"
861 "m = m * m;\n"
862 "return 42.0 * dot(m*m, vec4(dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3)));",
sugoi@google.comd537af52013-06-10 13:59:25 +0000863 taylorInvSqrtFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000864
sugoi@google.comd537af52013-06-10 13:59:25 +0000865 SkString noiseFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000866 builder->fsEmitFunction(kFloat_GrSLType,
867 "snoise", SK_ARRAY_COUNT(gNoiseVec3Args), gNoiseVec3Args,
868 noiseCode.c_str(), &noiseFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000869
870 const char* noiseVecIni = "noiseVecIni";
871 const char* factors = "factors";
872 const char* sum = "sum";
873 const char* xOffsets = "xOffsets";
874 const char* yOffsets = "yOffsets";
875 const char* channel = "channel";
876
877 // Fill with some prime numbers
878 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(13.0, 53.0, 101.0, 151.0);\n", xOffsets);
879 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(109.0, 167.0, 23.0, 67.0);\n", yOffsets);
880
881 // There are rounding errors if the floor operation is not performed here
882 builder->fsCodeAppendf(
883 "\t\tvec3 %s = vec3(floor((%s*vec3(%s, 1.0)).xy) * vec2(0.66) * %s, 0.0);\n",
commit-bot@chromium.org7ab7ca42013-08-28 15:59:13 +0000884 noiseVecIni, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000885
886 // Perturb the texcoords with three components of noise
887 builder->fsCodeAppendf("\t\t%s += 0.1 * vec3(%s(%s + vec3( 0.0, 0.0, %s)),"
888 "%s(%s + vec3( 43.0, 17.0, %s)),"
889 "%s(%s + vec3(-17.0, -43.0, %s)));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000890 noiseVecIni, noiseFuncName.c_str(), noiseVecIni, seedUni,
891 noiseFuncName.c_str(), noiseVecIni, seedUni,
892 noiseFuncName.c_str(), noiseVecIni, seedUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000893
894 builder->fsCodeAppendf("\t\t%s = vec4(0.0);\n", outputColor);
895
896 builder->fsCodeAppendf("\t\tvec3 %s = vec3(1.0);\n", factors);
897 builder->fsCodeAppendf("\t\tfloat %s = 0.0;\n", sum);
898
899 // Loop over all octaves
900 builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {\n", fNumOctaves);
901
902 // Loop over the 4 channels
903 builder->fsCodeAppendf("\t\t\tfor (int %s = 3; %s >= 0; --%s) {\n", channel, channel, channel);
904
905 builder->fsCodeAppendf(
906 "\t\t\t\t%s[channel] += %s.x * %s(%s * %s.yyy - vec3(%s[%s], %s[%s], %s * %s.z));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000907 outputColor, factors, noiseFuncName.c_str(), noiseVecIni, factors, xOffsets, channel,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000908 yOffsets, channel, seedUni, factors);
909
910 builder->fsCodeAppend("\t\t\t}\n"); // end of the for loop on channels
911
912 builder->fsCodeAppendf("\t\t\t%s += %s.x;\n", sum, factors);
913 builder->fsCodeAppendf("\t\t\t%s *= vec3(0.5, 2.0, 0.75);\n", factors);
914
915 builder->fsCodeAppend("\t\t}\n"); // end of the for loop on octaves
916
917 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
918 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
919 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
920 builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5 / %s) + vec4(0.5);\n",
921 outputColor, outputColor, sum);
922 } else {
923 builder->fsCodeAppendf("\t\t%s = abs(%s / vec4(%s));\n",
924 outputColor, outputColor, sum);
925 }
926
927 builder->fsCodeAppendf("\t\t%s.a *= %s;\n", outputColor, alphaUni);
928
929 // Clamp values
930 builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);\n", outputColor, outputColor);
931
932 // Pre-multiply the result
933 builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
934 outputColor, outputColor, outputColor, outputColor);
935}
936
sugoi@google.come3b4c502013-04-05 13:47:09 +0000937void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder,
938 const GrDrawEffect&,
939 EffectKey key,
940 const char* outputColor,
941 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000942 const TransformedCoordsArray& coords,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000943 const TextureSamplerArray& samplers) {
944 sk_ignore_unused_variable(inputColor);
945
bsalomon@google.com77af6802013-10-02 13:04:56 +0000946 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000947
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000948 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000949 kMat33f_GrSLType, "invMatrix");
950 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000951 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000952 kVec2f_GrSLType, "baseFrequency");
953 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000954 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000955 kFloat_GrSLType, "alpha");
956 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
957
958 const char* stitchDataUni = NULL;
959 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000960 fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
commit-bot@chromium.org98393202013-07-04 18:13:05 +0000961 kVec2f_GrSLType, "stitchData");
sugoi@google.come3b4c502013-04-05 13:47:09 +0000962 stitchDataUni = builder->getUniformCStr(fStitchDataUni);
963 }
964
sugoi@google.comd537af52013-06-10 13:59:25 +0000965 // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
966 const char* chanCoordR = "0.125";
967 const char* chanCoordG = "0.375";
968 const char* chanCoordB = "0.625";
969 const char* chanCoordA = "0.875";
970 const char* chanCoord = "chanCoord";
sugoi@google.come3b4c502013-04-05 13:47:09 +0000971 const char* stitchData = "stitchData";
972 const char* ratio = "ratio";
sugoi@google.come3b4c502013-04-05 13:47:09 +0000973 const char* noiseXY = "noiseXY";
974 const char* noiseVec = "noiseVec";
sugoi@google.come3b4c502013-04-05 13:47:09 +0000975 const char* noiseSmooth = "noiseSmooth";
976 const char* fractVal = "fractVal";
977 const char* uv = "uv";
978 const char* ab = "ab";
979 const char* latticeIdx = "latticeIdx";
980 const char* lattice = "lattice";
sugoi@google.come3b4c502013-04-05 13:47:09 +0000981 const char* inc8bit = "0.00390625"; // 1.0 / 256.0
982 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
983 // [-1,1] vector and perform a dot product between that vector and the provided vector.
984 const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
985
sugoi@google.comd537af52013-06-10 13:59:25 +0000986 // Add noise function
987 static const GrGLShaderVar gPerlinNoiseArgs[] = {
988 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +0000989 GrGLShaderVar(noiseVec, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +0000990 };
sugoi@google.come3b4c502013-04-05 13:47:09 +0000991
sugoi@google.comd537af52013-06-10 13:59:25 +0000992 static const GrGLShaderVar gPerlinNoiseStitchArgs[] = {
993 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +0000994 GrGLShaderVar(noiseVec, kVec2f_GrSLType),
995 GrGLShaderVar(stitchData, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +0000996 };
sugoi@google.come3b4c502013-04-05 13:47:09 +0000997
sugoi@google.comd537af52013-06-10 13:59:25 +0000998 SkString noiseCode;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000999
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001000 noiseCode.appendf("\tvec4 %s = vec4(floor(%s), fract(%s));", noiseXY, noiseVec, noiseVec);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001001
1002 // smooth curve : t * t * (3 - 2 * t)
sugoi@google.comd537af52013-06-10 13:59:25 +00001003 noiseCode.appendf("\n\tvec2 %s = %s.zw * %s.zw * (vec2(3.0) - vec2(2.0) * %s.zw);",
1004 noiseSmooth, noiseXY, noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001005
1006 // Adjust frequencies if we're stitching tiles
1007 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001008 noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001009 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001010 noiseCode.appendf("\n\tif(%s.x >= (%s.x - 1.0)) { %s.x -= (%s.x - 1.0); }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001011 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001012 noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001013 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001014 noiseCode.appendf("\n\tif(%s.y >= (%s.y - 1.0)) { %s.y -= (%s.y - 1.0); }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001015 noiseXY, stitchData, noiseXY, stitchData);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001016 }
1017
1018 // Get texture coordinates and normalize
sugoi@google.comd537af52013-06-10 13:59:25 +00001019 noiseCode.appendf("\n\t%s.xy = fract(floor(mod(%s.xy, 256.0)) / vec2(256.0));\n",
1020 noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001021
1022 // Get permutation for x
1023 {
1024 SkString xCoords("");
1025 xCoords.appendf("vec2(%s.x, 0.5)", noiseXY);
1026
sugoi@google.comd537af52013-06-10 13:59:25 +00001027 noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
1028 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1029 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001030 }
1031
1032 // Get permutation for x + 1
1033 {
1034 SkString xCoords("");
1035 xCoords.appendf("vec2(fract(%s.x + %s), 0.5)", noiseXY, inc8bit);
1036
sugoi@google.comd537af52013-06-10 13:59:25 +00001037 noiseCode.appendf("\n\t%s.y = ", latticeIdx);
1038 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1039 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001040 }
1041
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001042#if defined(SK_BUILD_FOR_ANDROID)
1043 // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
1044 // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
1045 // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
1046 // (or 0.484368 here). The following rounding operation prevents these precision issues from
1047 // affecting the result of the noise by making sure that we only have multiples of 1/255.
1048 // (Note that 1/255 is about 0.003921569, which is the value used here).
1049 noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);",
1050 latticeIdx, latticeIdx);
1051#endif
1052
sugoi@google.come3b4c502013-04-05 13:47:09 +00001053 // Get (x,y) coordinates with the permutated x
sugoi@google.comd537af52013-06-10 13:59:25 +00001054 noiseCode.appendf("\n\t%s = fract(%s + %s.yy);", latticeIdx, latticeIdx, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001055
sugoi@google.comd537af52013-06-10 13:59:25 +00001056 noiseCode.appendf("\n\tvec2 %s = %s.zw;", fractVal, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001057
sugoi@google.comd537af52013-06-10 13:59:25 +00001058 noiseCode.appendf("\n\n\tvec2 %s;", uv);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001059 // Compute u, at offset (0,0)
1060 {
1061 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001062 latticeCoords.appendf("vec2(%s.x, %s)", latticeIdx, chanCoord);
1063 noiseCode.appendf("\n\tvec4 %s = ", lattice);
1064 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1065 kVec2f_GrSLType);
1066 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1067 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001068 }
1069
sugoi@google.comd537af52013-06-10 13:59:25 +00001070 noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001071 // Compute v, at offset (-1,0)
1072 {
1073 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001074 latticeCoords.appendf("vec2(%s.y, %s)", latticeIdx, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001075 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001076 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1077 kVec2f_GrSLType);
1078 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1079 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001080 }
1081
1082 // Compute 'a' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001083 noiseCode.appendf("\n\tvec2 %s;", ab);
1084 noiseCode.appendf("\n\t%s.x = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001085
sugoi@google.comd537af52013-06-10 13:59:25 +00001086 noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001087 // Compute v, at offset (-1,-1)
1088 {
1089 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001090 latticeCoords.appendf("vec2(fract(%s.y + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001091 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001092 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1093 kVec2f_GrSLType);
1094 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1095 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001096 }
1097
sugoi@google.comd537af52013-06-10 13:59:25 +00001098 noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001099 // Compute u, at offset (0,-1)
1100 {
1101 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001102 latticeCoords.appendf("vec2(fract(%s.x + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001103 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001104 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1105 kVec2f_GrSLType);
1106 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1107 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001108 }
1109
1110 // Compute 'b' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001111 noiseCode.appendf("\n\t%s.y = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001112 // Compute the noise as a linear interpolation of 'a' and 'b'
sugoi@google.comd537af52013-06-10 13:59:25 +00001113 noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001114
sugoi@google.comd537af52013-06-10 13:59:25 +00001115 SkString noiseFuncName;
1116 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001117 builder->fsEmitFunction(kFloat_GrSLType,
1118 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
1119 gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001120 } else {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001121 builder->fsEmitFunction(kFloat_GrSLType,
1122 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
1123 gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001124 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001125
sugoi@google.comd537af52013-06-10 13:59:25 +00001126 // There are rounding errors if the floor operation is not performed here
1127 builder->fsCodeAppendf("\n\t\tvec2 %s = floor((%s * vec3(%s, 1.0)).xy) * %s;",
commit-bot@chromium.org7ab7ca42013-08-28 15:59:13 +00001128 noiseVec, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.comd537af52013-06-10 13:59:25 +00001129
1130 // Clear the color accumulator
1131 builder->fsCodeAppendf("\n\t\t%s = vec4(0.0);", outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001132
1133 if (fStitchTiles) {
sugoi@google.comd537af52013-06-10 13:59:25 +00001134 // Set up TurbulenceInitial stitch values.
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001135 builder->fsCodeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001136 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001137
sugoi@google.comd537af52013-06-10 13:59:25 +00001138 builder->fsCodeAppendf("\n\t\tfloat %s = 1.0;", ratio);
1139
1140 // Loop over all octaves
1141 builder->fsCodeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
1142
1143 builder->fsCodeAppendf("\n\t\t\t%s += ", outputColor);
1144 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1145 builder->fsCodeAppend("abs(");
1146 }
1147 if (fStitchTiles) {
1148 builder->fsCodeAppendf(
1149 "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
1150 "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
1151 noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
1152 noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
1153 noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
1154 noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
1155 } else {
1156 builder->fsCodeAppendf(
1157 "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
1158 "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
1159 noiseFuncName.c_str(), chanCoordR, noiseVec,
1160 noiseFuncName.c_str(), chanCoordG, noiseVec,
1161 noiseFuncName.c_str(), chanCoordB, noiseVec,
1162 noiseFuncName.c_str(), chanCoordA, noiseVec);
1163 }
1164 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1165 builder->fsCodeAppendf(")"); // end of "abs("
1166 }
1167 builder->fsCodeAppendf(" * %s;", ratio);
1168
1169 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
1170 builder->fsCodeAppendf("\n\t\t\t%s *= 0.5;", ratio);
1171
1172 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001173 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData);
sugoi@google.comd537af52013-06-10 13:59:25 +00001174 }
1175 builder->fsCodeAppend("\n\t\t}"); // end of the for loop on octaves
sugoi@google.come3b4c502013-04-05 13:47:09 +00001176
1177 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
1178 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
1179 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
sugoi@google.comd537af52013-06-10 13:59:25 +00001180 builder->fsCodeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001181 }
1182
sugoi@google.comd537af52013-06-10 13:59:25 +00001183 builder->fsCodeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001184
1185 // Clamp values
sugoi@google.comd537af52013-06-10 13:59:25 +00001186 builder->fsCodeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001187
1188 // Pre-multiply the result
sugoi@google.comd537af52013-06-10 13:59:25 +00001189 builder->fsCodeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
sugoi@google.come3b4c502013-04-05 13:47:09 +00001190 outputColor, outputColor, outputColor, outputColor);
1191}
1192
sugoi@google.com4775cba2013-04-17 13:46:56 +00001193GrGLNoise::GrGLNoise(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect)
sugoi@google.come3b4c502013-04-05 13:47:09 +00001194 : INHERITED (factory)
1195 , fType(drawEffect.castEffect<GrPerlinNoiseEffect>().type())
1196 , fStitchTiles(drawEffect.castEffect<GrPerlinNoiseEffect>().stitchTiles())
bsalomon@google.com77af6802013-10-02 13:04:56 +00001197 , fNumOctaves(drawEffect.castEffect<GrPerlinNoiseEffect>().numOctaves()) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001198}
1199
sugoi@google.com4775cba2013-04-17 13:46:56 +00001200GrGLEffect::EffectKey GrGLNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001201 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1202
1203 EffectKey key = turbulence.numOctaves();
1204
1205 key = key << 3; // Make room for next 3 bits
1206
1207 switch (turbulence.type()) {
1208 case SkPerlinNoiseShader::kFractalNoise_Type:
1209 key |= 0x1;
1210 break;
1211 case SkPerlinNoiseShader::kTurbulence_Type:
1212 key |= 0x2;
1213 break;
1214 default:
1215 // leave key at 0
1216 break;
1217 }
1218
1219 if (turbulence.stitchTiles()) {
1220 key |= 0x4; // Flip the 3rd bit if tile stitching is on
1221 }
1222
bsalomon@google.com77af6802013-10-02 13:04:56 +00001223 return key;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001224}
1225
sugoi@google.com4775cba2013-04-17 13:46:56 +00001226void GrGLNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001227 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1228
1229 const SkVector& baseFrequency = turbulence.baseFrequency();
1230 uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001231 uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
1232
1233 SkMatrix m = turbulence.matrix();
bsalomon@google.com77af6802013-10-02 13:04:56 +00001234 m.postTranslate(-SK_Scalar1, -SK_Scalar1);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001235 SkMatrix invM;
1236 if (!m.invert(&invM)) {
1237 invM.reset();
1238 } else {
1239 invM.postConcat(invM); // Square the matrix
1240 }
1241 uman.setSkMatrix(fInvMatrixUni, invM);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001242}
1243
sugoi@google.com4775cba2013-04-17 13:46:56 +00001244void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1245 INHERITED::setData(uman, drawEffect);
1246
1247 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1248 if (turbulence.stitchTiles()) {
1249 const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001250 uman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
1251 SkIntToScalar(stitchData.fHeight));
sugoi@google.com4775cba2013-04-17 13:46:56 +00001252 }
1253}
1254
1255void GrGLSimplexNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1256 INHERITED::setData(uman, drawEffect);
1257
1258 const GrSimplexNoiseEffect& turbulence = drawEffect.castEffect<GrSimplexNoiseEffect>();
1259 uman.set1f(fSeedUni, turbulence.seed());
1260}
1261
sugoi@google.come3b4c502013-04-05 13:47:09 +00001262/////////////////////////////////////////////////////////////////////
1263
1264GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001265 SkASSERT(NULL != context);
1266
commit-bot@chromium.orgc2a0ea62013-11-06 10:08:38 +00001267 if (0 == fNumOctaves) {
1268 SkColor clearColor = 0;
1269 if (kFractalNoise_Type == fType) {
1270 clearColor = SkColorSetARGB(paint.getAlpha() / 2, 127, 127, 127);
1271 }
1272 SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(
1273 clearColor, SkXfermode::kSrc_Mode));
1274 return cf->asNewEffect(context);
1275 }
1276
sugoi@google.come3b4c502013-04-05 13:47:09 +00001277 // Either we don't stitch tiles, either we have a valid tile size
1278 SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
1279
sugoi@google.com4775cba2013-04-17 13:46:56 +00001280#ifdef SK_USE_SIMPLEX_NOISE
1281 // Simplex noise is currently disabled but can be enabled by defining SK_USE_SIMPLEX_NOISE
1282 sk_ignore_unused_variable(context);
1283 GrEffectRef* effect =
1284 GrSimplexNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
1285 fNumOctaves, fStitchTiles, fSeed,
1286 this->getLocalMatrix(), paint.getAlpha());
1287#else
sugoi@google.come3b4c502013-04-05 13:47:09 +00001288 GrTexture* permutationsTexture = GrLockAndRefCachedBitmapTexture(
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +00001289 context, fPaintingData->getPermutationsBitmap(), NULL);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001290 GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture(
commit-bot@chromium.orgfd5c9a62014-03-06 15:13:53 +00001291 context, fPaintingData->getNoiseBitmap(), NULL);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001292
1293 GrEffectRef* effect = (NULL != permutationsTexture) && (NULL != noiseTexture) ?
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001294 GrPerlinNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001295 fNumOctaves, fStitchTiles,
1296 fPaintingData->fStitchDataInit,
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001297 permutationsTexture, noiseTexture,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001298 this->getLocalMatrix(), paint.getAlpha()) :
1299 NULL;
1300
1301 // Unlock immediately, this is not great, but we don't have a way of
1302 // knowing when else to unlock it currently. TODO: Remove this when
1303 // unref becomes the unlock replacement for all types of textures.
1304 if (NULL != permutationsTexture) {
1305 GrUnlockAndUnrefCachedBitmapTexture(permutationsTexture);
1306 }
1307 if (NULL != noiseTexture) {
1308 GrUnlockAndUnrefCachedBitmapTexture(noiseTexture);
1309 }
sugoi@google.com4775cba2013-04-17 13:46:56 +00001310#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +00001311
1312 return effect;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001313}
1314
1315#else
1316
1317GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext*, const SkPaint&) const {
1318 SkDEBUGFAIL("Should not call in GPU-less build");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001319 return NULL;
1320}
1321
1322#endif
1323
commit-bot@chromium.org0f10f7b2014-03-13 18:02:17 +00001324#ifndef SK_IGNORE_TO_STRING
sugoi@google.come3b4c502013-04-05 13:47:09 +00001325void SkPerlinNoiseShader::toString(SkString* str) const {
1326 str->append("SkPerlinNoiseShader: (");
1327
1328 str->append("type: ");
1329 switch (fType) {
1330 case kFractalNoise_Type:
1331 str->append("\"fractal noise\"");
1332 break;
1333 case kTurbulence_Type:
1334 str->append("\"turbulence\"");
1335 break;
1336 default:
1337 str->append("\"unknown\"");
1338 break;
1339 }
1340 str->append(" base frequency: (");
1341 str->appendScalar(fBaseFrequencyX);
1342 str->append(", ");
1343 str->appendScalar(fBaseFrequencyY);
1344 str->append(") number of octaves: ");
1345 str->appendS32(fNumOctaves);
1346 str->append(" seed: ");
1347 str->appendScalar(fSeed);
1348 str->append(" stitch tiles: ");
1349 str->append(fStitchTiles ? "true " : "false ");
1350
1351 this->INHERITED::toString(str);
1352
1353 str->append(")");
1354}
1355#endif