blob: bbd550a6a3cdc9588691b0ae47b81caa42a7f2a9 [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"
10#include "SkFlattenableBuffers.h"
11#include "SkShader.h"
12#include "SkUnPreMultiply.h"
13#include "SkString.h"
14
15#if SK_SUPPORT_GPU
16#include "GrContext.h"
17#include "gl/GrGLEffect.h"
18#include "gl/GrGLEffectMatrix.h"
19#include "GrTBackendEffectFactory.h"
20#include "SkGr.h"
21#endif
22
23static const int kBlockSize = 256;
24static const int kBlockMask = kBlockSize - 1;
25static const int kPerlinNoise = 4096;
26static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
27
28namespace {
29
30// noiseValue is the color component's value (or color)
31// limitValue is the maximum perlin noise array index value allowed
32// newValue is the current noise dimension (either width or height)
33inline int checkNoise(int noiseValue, int limitValue, int newValue) {
34 // If the noise value would bring us out of bounds of the current noise array while we are
35 // stiching noise tiles together, wrap the noise around the current dimension of the noise to
36 // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
37 if (noiseValue >= limitValue) {
38 noiseValue -= newValue;
39 }
40 if (noiseValue >= limitValue - 1) {
41 noiseValue -= newValue - 1;
42 }
43 return noiseValue;
44}
45
46inline SkScalar smoothCurve(SkScalar t) {
47 static const SkScalar SK_Scalar3 = SkFloatToScalar(3.0f);
48
49 // returns t * t * (3 - 2 * t)
50 return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
51}
52
53} // end namespace
54
55struct SkPerlinNoiseShader::StitchData {
56 StitchData()
57 : fWidth(0)
58 , fWrapX(0)
59 , fHeight(0)
60 , fWrapY(0)
61 {}
62
63 bool operator==(const StitchData& other) const {
64 return fWidth == other.fWidth &&
65 fWrapX == other.fWrapX &&
66 fHeight == other.fHeight &&
67 fWrapY == other.fWrapY;
68 }
69
70 int fWidth; // How much to subtract to wrap for stitching.
71 int fWrapX; // Minimum value to wrap.
72 int fHeight;
73 int fWrapY;
74};
75
76struct SkPerlinNoiseShader::PaintingData {
77 PaintingData(const SkISize& tileSize)
78 : fSeed(0)
79 , fTileSize(tileSize)
80 , fPermutationsBitmap(NULL)
81 , fNoiseBitmap(NULL)
82 {}
83
84 ~PaintingData()
85 {
86 SkDELETE(fPermutationsBitmap);
87 SkDELETE(fNoiseBitmap);
88 }
89
90 int fSeed;
91 uint8_t fLatticeSelector[kBlockSize];
92 uint16_t fNoise[4][kBlockSize][2];
93 SkPoint fGradient[4][kBlockSize];
94 SkISize fTileSize;
95 SkVector fBaseFrequency;
96 StitchData fStitchDataInit;
97
98private:
99
100 SkBitmap* fPermutationsBitmap;
101 SkBitmap* fNoiseBitmap;
102
103public:
104
105 inline int random() {
106 static const int gRandAmplitude = 16807; // 7**5; primitive root of m
107 static const int gRandQ = 127773; // m / a
108 static const int gRandR = 2836; // m % a
109
110 int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
111 if (result <= 0)
112 result += kRandMaximum;
113 fSeed = result;
114 return result;
115 }
116
117 void init(SkScalar seed)
118 {
119 static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
120
121 // The seed value clamp to the range [1, kRandMaximum - 1].
122 fSeed = SkScalarRoundToInt(seed);
123 if (fSeed <= 0) {
124 fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
125 }
126 if (fSeed > kRandMaximum - 1) {
127 fSeed = kRandMaximum - 1;
128 }
129 for (int channel = 0; channel < 4; ++channel) {
130 for (int i = 0; i < kBlockSize; ++i) {
131 fLatticeSelector[i] = i;
132 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
133 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
134 }
135 }
136 for (int i = kBlockSize - 1; i > 0; --i) {
137 int k = fLatticeSelector[i];
138 int j = random() % kBlockSize;
139 SkASSERT(j >= 0);
140 SkASSERT(j < kBlockSize);
141 fLatticeSelector[i] = fLatticeSelector[j];
142 fLatticeSelector[j] = k;
143 }
144
145 // Perform the permutations now
146 {
147 // Copy noise data
148 uint16_t noise[4][kBlockSize][2];
149 for (int i = 0; i < kBlockSize; ++i) {
150 for (int channel = 0; channel < 4; ++channel) {
151 for (int j = 0; j < 2; ++j) {
152 noise[channel][i][j] = fNoise[channel][i][j];
153 }
154 }
155 }
156 // Do permutations on noise data
157 for (int i = 0; i < kBlockSize; ++i) {
158 for (int channel = 0; channel < 4; ++channel) {
159 for (int j = 0; j < 2; ++j) {
160 fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
161 }
162 }
163 }
164 }
165
166 // Half of the largest possible value for 16 bit unsigned int
sugoi@google.comd537af52013-06-10 13:59:25 +0000167 static const SkScalar gHalfMax16bits = SkFloatToScalar(32767.5f);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000168
169 // Compute gradients from permutated noise data
170 for (int channel = 0; channel < 4; ++channel) {
171 for (int i = 0; i < kBlockSize; ++i) {
172 fGradient[channel][i] = SkPoint::Make(
173 SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
174 gInvBlockSizef),
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000175 SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
sugoi@google.come3b4c502013-04-05 13:47:09 +0000176 gInvBlockSizef));
177 fGradient[channel][i].normalize();
178 // Put the normalized gradient back into the noise data
179 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000180 fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000181 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000182 fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000183 }
184 }
185
186 // Invalidate bitmaps
187 SkDELETE(fPermutationsBitmap);
188 fPermutationsBitmap = NULL;
189 SkDELETE(fNoiseBitmap);
190 fNoiseBitmap = NULL;
191 }
192
193 void stitch() {
194 SkScalar tileWidth = SkIntToScalar(fTileSize.width());
195 SkScalar tileHeight = SkIntToScalar(fTileSize.height());
196 SkASSERT(tileWidth > 0 && tileHeight > 0);
197 // When stitching tiled turbulence, the frequencies must be adjusted
198 // so that the tile borders will be continuous.
199 if (fBaseFrequency.fX) {
200 SkScalar lowFrequencx = SkScalarDiv(
201 SkScalarMulFloor(tileWidth, fBaseFrequency.fX), tileWidth);
202 SkScalar highFrequencx = SkScalarDiv(
203 SkScalarMulCeil(tileWidth, fBaseFrequency.fX), tileWidth);
204 // BaseFrequency should be non-negative according to the standard.
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000205 if (SkScalarDiv(fBaseFrequency.fX, lowFrequencx) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000206 SkScalarDiv(highFrequencx, fBaseFrequency.fX)) {
207 fBaseFrequency.fX = lowFrequencx;
208 } else {
209 fBaseFrequency.fX = highFrequencx;
210 }
211 }
212 if (fBaseFrequency.fY) {
213 SkScalar lowFrequency = SkScalarDiv(
214 SkScalarMulFloor(tileHeight, fBaseFrequency.fY), tileHeight);
215 SkScalar highFrequency = SkScalarDiv(
216 SkScalarMulCeil(tileHeight, fBaseFrequency.fY), tileHeight);
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000217 if (SkScalarDiv(fBaseFrequency.fY, lowFrequency) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000218 SkScalarDiv(highFrequency, fBaseFrequency.fY)) {
219 fBaseFrequency.fY = lowFrequency;
220 } else {
221 fBaseFrequency.fY = highFrequency;
222 }
223 }
224 // Set up TurbulenceInitial stitch values.
225 fStitchDataInit.fWidth =
226 SkScalarMulRound(tileWidth, fBaseFrequency.fX);
227 fStitchDataInit.fWrapX = kPerlinNoise + fStitchDataInit.fWidth;
228 fStitchDataInit.fHeight =
229 SkScalarMulRound(tileHeight, fBaseFrequency.fY);
230 fStitchDataInit.fWrapY = kPerlinNoise + fStitchDataInit.fHeight;
231 }
232
233 SkBitmap* getPermutationsBitmap()
234 {
235 if (!fPermutationsBitmap) {
236 fPermutationsBitmap = SkNEW(SkBitmap);
237 fPermutationsBitmap->setConfig(SkBitmap::kA8_Config, kBlockSize, 1);
238 fPermutationsBitmap->allocPixels();
239 uint8_t* bitmapPixels = fPermutationsBitmap->getAddr8(0, 0);
240 memcpy(bitmapPixels, fLatticeSelector, sizeof(uint8_t) * kBlockSize);
241 }
242 return fPermutationsBitmap;
243 }
244
245 SkBitmap* getNoiseBitmap()
246 {
247 if (!fNoiseBitmap) {
248 fNoiseBitmap = SkNEW(SkBitmap);
249 fNoiseBitmap->setConfig(SkBitmap::kARGB_8888_Config, kBlockSize, 4);
250 fNoiseBitmap->allocPixels();
251 uint32_t* bitmapPixels = fNoiseBitmap->getAddr32(0, 0);
252 memcpy(bitmapPixels, fNoise[0][0], sizeof(uint16_t) * kBlockSize * 4 * 2);
253 }
254 return fNoiseBitmap;
255 }
256};
257
258SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
259 int numOctaves, SkScalar seed,
260 const SkISize* tileSize) {
261 return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY,
262 numOctaves, seed, tileSize));
263}
264
265SkShader* SkPerlinNoiseShader::CreateTubulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
266 int numOctaves, SkScalar seed,
267 const SkISize* tileSize) {
268 return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY,
269 numOctaves, seed, tileSize));
270}
271
272SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
273 SkScalar baseFrequencyX,
274 SkScalar baseFrequencyY,
275 int numOctaves,
276 SkScalar seed,
277 const SkISize* tileSize)
278 : fType(type)
279 , fBaseFrequencyX(baseFrequencyX)
280 , fBaseFrequencyY(baseFrequencyY)
281 , fNumOctaves(numOctaves & 0xFF /*[0,255] octaves allowed*/)
282 , fSeed(seed)
283 , fStitchTiles((tileSize != NULL) && !tileSize->isEmpty())
284 , fPaintingData(NULL)
285{
286 SkASSERT(numOctaves >= 0 && numOctaves < 256);
287 setTileSize(fStitchTiles ? *tileSize : SkISize::Make(0,0));
288 fMatrix.reset();
289}
290
291SkPerlinNoiseShader::SkPerlinNoiseShader(SkFlattenableReadBuffer& buffer) :
292 INHERITED(buffer), fPaintingData(NULL) {
293 fType = (SkPerlinNoiseShader::Type) buffer.readInt();
294 fBaseFrequencyX = buffer.readScalar();
295 fBaseFrequencyY = buffer.readScalar();
296 fNumOctaves = buffer.readInt();
297 fSeed = buffer.readScalar();
298 fStitchTiles = buffer.readBool();
299 fTileSize.fWidth = buffer.readInt();
300 fTileSize.fHeight = buffer.readInt();
301 setTileSize(fTileSize);
302 fMatrix.reset();
303}
304
305SkPerlinNoiseShader::~SkPerlinNoiseShader() {
306 // Safety, should have been done in endContext()
307 SkDELETE(fPaintingData);
308}
309
310void SkPerlinNoiseShader::flatten(SkFlattenableWriteBuffer& buffer) const {
311 this->INHERITED::flatten(buffer);
312 buffer.writeInt((int) fType);
313 buffer.writeScalar(fBaseFrequencyX);
314 buffer.writeScalar(fBaseFrequencyY);
315 buffer.writeInt(fNumOctaves);
316 buffer.writeScalar(fSeed);
317 buffer.writeBool(fStitchTiles);
318 buffer.writeInt(fTileSize.fWidth);
319 buffer.writeInt(fTileSize.fHeight);
320}
321
322void SkPerlinNoiseShader::initPaint(PaintingData& paintingData)
323{
324 paintingData.init(fSeed);
325
326 // Set frequencies to original values
327 paintingData.fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
328 // Adjust frequecies based on size if stitching is enabled
329 if (fStitchTiles) {
330 paintingData.stitch();
331 }
332}
333
334void SkPerlinNoiseShader::setTileSize(const SkISize& tileSize) {
335 fTileSize = tileSize;
336
337 if (NULL == fPaintingData) {
338 fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize));
339 initPaint(*fPaintingData);
340 } else {
341 // Set Size
342 fPaintingData->fTileSize = fTileSize;
343 // Set frequencies to original values
344 fPaintingData->fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
345 // Adjust frequecies based on size if stitching is enabled
346 if (fStitchTiles) {
347 fPaintingData->stitch();
348 }
349 }
350}
351
352SkScalar SkPerlinNoiseShader::noise2D(int channel, const PaintingData& paintingData,
353 const StitchData& stitchData, const SkPoint& noiseVector)
354{
355 struct Noise {
356 int noisePositionIntegerValue;
357 SkScalar noisePositionFractionValue;
358 Noise(SkScalar component)
359 {
360 SkScalar position = component + kPerlinNoise;
361 noisePositionIntegerValue = SkScalarFloorToInt(position);
362 noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
363 }
364 };
365 Noise noiseX(noiseVector.x());
366 Noise noiseY(noiseVector.y());
367 SkScalar u, v;
368 // If stitching, adjust lattice points accordingly.
369 if (fStitchTiles) {
370 noiseX.noisePositionIntegerValue =
371 checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
372 noiseY.noisePositionIntegerValue =
373 checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
374 }
375 noiseX.noisePositionIntegerValue &= kBlockMask;
376 noiseY.noisePositionIntegerValue &= kBlockMask;
377 int latticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000378 paintingData.fLatticeSelector[noiseX.noisePositionIntegerValue] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000379 noiseY.noisePositionIntegerValue;
380 int nextLatticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000381 paintingData.fLatticeSelector[(noiseX.noisePositionIntegerValue + 1) & kBlockMask] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000382 noiseY.noisePositionIntegerValue;
383 SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
384 SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
385 // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
386 SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
387 noiseY.noisePositionFractionValue); // Offset (0,0)
388 u = paintingData.fGradient[channel][latticeIndex & kBlockMask].dot(fractionValue);
389 fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
390 v = paintingData.fGradient[channel][nextLatticeIndex & kBlockMask].dot(fractionValue);
391 SkScalar a = SkScalarInterp(u, v, sx);
392 fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
393 v = paintingData.fGradient[channel][(nextLatticeIndex + 1) & kBlockMask].dot(fractionValue);
394 fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
395 u = paintingData.fGradient[channel][(latticeIndex + 1) & kBlockMask].dot(fractionValue);
396 SkScalar b = SkScalarInterp(u, v, sx);
397 return SkScalarInterp(a, b, sy);
398}
399
400SkScalar SkPerlinNoiseShader::calculateTurbulenceValueForPoint(
401 int channel, const PaintingData& paintingData, StitchData& stitchData, const SkPoint& point)
402{
403 if (fStitchTiles) {
404 // Set up TurbulenceInitial stitch values.
405 stitchData = paintingData.fStitchDataInit;
406 }
407 SkScalar turbulenceFunctionResult = 0;
408 SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), paintingData.fBaseFrequency.fX),
409 SkScalarMul(point.y(), paintingData.fBaseFrequency.fY)));
410 SkScalar ratio = SK_Scalar1;
411 for (int octave = 0; octave < fNumOctaves; ++octave) {
412 SkScalar noise = noise2D(channel, paintingData, stitchData, noiseVector);
413 turbulenceFunctionResult += SkScalarDiv(
414 (fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio);
415 noiseVector.fX *= 2;
416 noiseVector.fY *= 2;
417 ratio *= 2;
418 if (fStitchTiles) {
419 // Update stitch values
420 stitchData.fWidth *= 2;
421 stitchData.fWrapX = stitchData.fWidth + kPerlinNoise;
422 stitchData.fHeight *= 2;
423 stitchData.fWrapY = stitchData.fHeight + kPerlinNoise;
424 }
425 }
426
427 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
428 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
429 if (fType == kFractalNoise_Type) {
430 turbulenceFunctionResult =
431 SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
432 }
433
434 if (channel == 3) { // Scale alpha by paint value
435 turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult,
436 SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255)));
437 }
438
439 // Clamp result
440 return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
441}
442
443SkPMColor SkPerlinNoiseShader::shade(const SkPoint& point, StitchData& stitchData) {
444 SkMatrix matrix = fMatrix;
445 SkMatrix invMatrix;
446 if (!matrix.invert(&invMatrix)) {
447 invMatrix.reset();
448 } else {
449 invMatrix.postConcat(invMatrix); // Square the matrix
450 }
451 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
452 // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
453 matrix.postTranslate(SK_Scalar1, SK_Scalar1);
454 SkPoint newPoint;
455 matrix.mapPoints(&newPoint, &point, 1);
456 invMatrix.mapPoints(&newPoint, &newPoint, 1);
457 newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
458 newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
459
460 U8CPU rgba[4];
461 for (int channel = 3; channel >= 0; --channel) {
462 rgba[channel] = SkScalarFloorToInt(255 *
463 calculateTurbulenceValueForPoint(channel, *fPaintingData, stitchData, newPoint));
464 }
465 return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
466}
467
468bool SkPerlinNoiseShader::setContext(const SkBitmap& device, const SkPaint& paint,
469 const SkMatrix& matrix) {
470 fMatrix = matrix;
471 return INHERITED::setContext(device, paint, matrix);
472}
473
474void SkPerlinNoiseShader::shadeSpan(int x, int y, SkPMColor result[], int count) {
475 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
476 StitchData stitchData;
477 for (int i = 0; i < count; ++i) {
478 result[i] = shade(point, stitchData);
479 point.fX += SK_Scalar1;
480 }
481}
482
483void SkPerlinNoiseShader::shadeSpan16(int x, int y, uint16_t result[], int count) {
484 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
485 StitchData stitchData;
486 DITHER_565_SCAN(y);
487 for (int i = 0; i < count; ++i) {
488 unsigned dither = DITHER_VALUE(x);
489 result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
490 DITHER_INC_X(x);
491 point.fX += SK_Scalar1;
492 }
493}
494
495/////////////////////////////////////////////////////////////////////
496
sugoi@google.comd537af52013-06-10 13:59:25 +0000497#if SK_SUPPORT_GPU && !defined(SK_BUILD_FOR_ANDROID)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000498// CPU noise is faster on Android, so the GPU implementation is only for desktop
sugoi@google.come3b4c502013-04-05 13:47:09 +0000499
500#include "GrTBackendEffectFactory.h"
501
sugoi@google.com4775cba2013-04-17 13:46:56 +0000502class GrGLNoise : public GrGLEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000503public:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000504 GrGLNoise(const GrBackendEffectFactory& factory,
505 const GrDrawEffect& drawEffect);
506 virtual ~GrGLNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000507
sugoi@google.com4775cba2013-04-17 13:46:56 +0000508 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
509
510 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
511
512protected:
513 SkPerlinNoiseShader::Type fType;
514 bool fStitchTiles;
515 int fNumOctaves;
516 GrGLUniformManager::UniformHandle fBaseFrequencyUni;
517 GrGLUniformManager::UniformHandle fAlphaUni;
518 GrGLUniformManager::UniformHandle fInvMatrixUni;
519 GrGLEffectMatrix fEffectMatrix;
520
521private:
522 typedef GrGLEffect INHERITED;
523};
524
525class GrGLPerlinNoise : public GrGLNoise {
526public:
sugoi@google.come3b4c502013-04-05 13:47:09 +0000527 GrGLPerlinNoise(const GrBackendEffectFactory& factory,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000528 const GrDrawEffect& drawEffect)
529 : GrGLNoise(factory, drawEffect) {}
530 virtual ~GrGLPerlinNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000531
532 virtual void emitCode(GrGLShaderBuilder*,
533 const GrDrawEffect&,
534 EffectKey,
535 const char* outputColor,
536 const char* inputColor,
537 const TextureSamplerArray&) SK_OVERRIDE;
538
sugoi@google.com4775cba2013-04-17 13:46:56 +0000539 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000540
541private:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000542 GrGLUniformManager::UniformHandle fStitchDataUni;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000543
sugoi@google.com4775cba2013-04-17 13:46:56 +0000544 typedef GrGLNoise INHERITED;
545};
546
547class GrGLSimplexNoise : public GrGLNoise {
548 // Note : This is for reference only. GrGLPerlinNoise is used for processing.
549public:
550 GrGLSimplexNoise(const GrBackendEffectFactory& factory,
551 const GrDrawEffect& drawEffect)
552 : GrGLNoise(factory, drawEffect) {}
553
554 virtual ~GrGLSimplexNoise() {}
555
556 virtual void emitCode(GrGLShaderBuilder*,
557 const GrDrawEffect&,
558 EffectKey,
559 const char* outputColor,
560 const char* inputColor,
561 const TextureSamplerArray&) SK_OVERRIDE;
562
563 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
564
565private:
566 GrGLUniformManager::UniformHandle fSeedUni;
567
568 typedef GrGLNoise INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000569};
570
571/////////////////////////////////////////////////////////////////////
572
sugoi@google.com4775cba2013-04-17 13:46:56 +0000573class GrNoiseEffect : public GrEffect {
574public:
575 virtual ~GrNoiseEffect() { }
576
577 SkPerlinNoiseShader::Type type() const { return fType; }
578 bool stitchTiles() const { return fStitchTiles; }
579 const SkVector& baseFrequency() const { return fBaseFrequency; }
580 int numOctaves() const { return fNumOctaves; }
581 const SkMatrix& matrix() const { return fMatrix; }
582 uint8_t alpha() const { return fAlpha; }
583 GrGLEffectMatrix::CoordsType coordsType() const { return GrEffect::kLocal_CoordsType; }
584
585 void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE {
586 *validFlags = 0; // This is noise. Nothing is constant.
587 }
588
589protected:
590 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
591 const GrNoiseEffect& s = CastEffect<GrNoiseEffect>(sBase);
592 return fType == s.fType &&
593 fBaseFrequency == s.fBaseFrequency &&
594 fNumOctaves == s.fNumOctaves &&
595 fStitchTiles == s.fStitchTiles &&
596 fMatrix == s.fMatrix &&
597 fAlpha == s.fAlpha;
598 }
599
600 GrNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, int numOctaves,
601 bool stitchTiles, const SkMatrix& matrix, uint8_t alpha)
602 : fType(type)
603 , fBaseFrequency(baseFrequency)
604 , fNumOctaves(numOctaves)
605 , fStitchTiles(stitchTiles)
606 , fMatrix(matrix)
607 , fAlpha(alpha) {
608 }
609
610 SkPerlinNoiseShader::Type fType;
611 SkVector fBaseFrequency;
612 int fNumOctaves;
613 bool fStitchTiles;
614 SkMatrix fMatrix;
615 uint8_t fAlpha;
616
617private:
618 typedef GrEffect INHERITED;
619};
620
621class GrPerlinNoiseEffect : public GrNoiseEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000622public:
623 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
624 int numOctaves, bool stitchTiles,
625 const SkPerlinNoiseShader::StitchData& stitchData,
626 GrTexture* permutationsTexture, GrTexture* noiseTexture,
627 const SkMatrix& matrix, uint8_t alpha) {
628 AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves,
629 stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha)));
630 return CreateEffectRef(effect);
631 }
632
633 virtual ~GrPerlinNoiseEffect() { }
634
635 static const char* Name() { return "PerlinNoise"; }
636 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
637 return GrTBackendEffectFactory<GrPerlinNoiseEffect>::getInstance();
638 }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000639 const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000640
641 typedef GrGLPerlinNoise GLEffect;
642
sugoi@google.come3b4c502013-04-05 13:47:09 +0000643private:
644 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
645 const GrPerlinNoiseEffect& s = CastEffect<GrPerlinNoiseEffect>(sBase);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000646 return INHERITED::onIsEqual(sBase) &&
647 fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() &&
sugoi@google.come3b4c502013-04-05 13:47:09 +0000648 fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000649 fStitchData == s.fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000650 }
651
652 GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
653 int numOctaves, bool stitchTiles,
654 const SkPerlinNoiseShader::StitchData& stitchData,
655 GrTexture* permutationsTexture, GrTexture* noiseTexture,
656 const SkMatrix& matrix, uint8_t alpha)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000657 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
658 , fPermutationsAccess(permutationsTexture)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000659 , fNoiseAccess(noiseTexture)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000660 , fStitchData(stitchData) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000661 this->addTextureAccess(&fPermutationsAccess);
662 this->addTextureAccess(&fNoiseAccess);
663 }
664
sugoi@google.com4775cba2013-04-17 13:46:56 +0000665 GR_DECLARE_EFFECT_TEST;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000666
667 GrTextureAccess fPermutationsAccess;
668 GrTextureAccess fNoiseAccess;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000669 SkPerlinNoiseShader::StitchData fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000670
sugoi@google.com4775cba2013-04-17 13:46:56 +0000671 typedef GrNoiseEffect INHERITED;
672};
673
674class GrSimplexNoiseEffect : public GrNoiseEffect {
675 // Note : This is for reference only. GrPerlinNoiseEffect is used for processing.
676public:
677 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
678 int numOctaves, bool stitchTiles, const SkScalar seed,
679 const SkMatrix& matrix, uint8_t alpha) {
680 AutoEffectUnref effect(SkNEW_ARGS(GrSimplexNoiseEffect, (type, baseFrequency, numOctaves,
681 stitchTiles, seed, matrix, alpha)));
682 return CreateEffectRef(effect);
683 }
684
685 virtual ~GrSimplexNoiseEffect() { }
686
687 static const char* Name() { return "SimplexNoise"; }
688 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
689 return GrTBackendEffectFactory<GrSimplexNoiseEffect>::getInstance();
690 }
691 const SkScalar& seed() const { return fSeed; }
692
693 typedef GrGLSimplexNoise GLEffect;
694
695private:
696 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
697 const GrSimplexNoiseEffect& s = CastEffect<GrSimplexNoiseEffect>(sBase);
698 return INHERITED::onIsEqual(sBase) && fSeed == s.fSeed;
699 }
700
701 GrSimplexNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
702 int numOctaves, bool stitchTiles, const SkScalar seed,
703 const SkMatrix& matrix, uint8_t alpha)
704 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
705 , fSeed(seed) {
706 }
707
708 SkScalar fSeed;
709
710 typedef GrNoiseEffect INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000711};
712
713/////////////////////////////////////////////////////////////////////
sugoi@google.come3b4c502013-04-05 13:47:09 +0000714GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect);
715
716GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkMWCRandom* random,
717 GrContext* context,
718 const GrDrawTargetCaps&,
719 GrTexture**) {
sugoi@google.com423ac132013-04-18 14:04:57 +0000720 int numOctaves = random->nextRangeU(2, 10);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000721 bool stitchTiles = random->nextBool();
722 SkScalar seed = SkIntToScalar(random->nextU());
723 SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
724 SkScalar baseFrequencyX = random->nextRangeScalar(SkFloatToScalar(0.01f),
725 SkFloatToScalar(0.99f));
726 SkScalar baseFrequencyY = random->nextRangeScalar(SkFloatToScalar(0.01f),
727 SkFloatToScalar(0.99f));
728
729 SkShader* shader = random->nextBool() ?
730 SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
731 stitchTiles ? &tileSize : NULL) :
732 SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
733 stitchTiles ? &tileSize : NULL);
734
735 SkPaint paint;
736 GrEffectRef* effect = shader->asNewEffect(context, paint);
737
738 SkDELETE(shader);
739
740 return effect;
741}
sugoi@google.com4775cba2013-04-17 13:46:56 +0000742
sugoi@google.come3b4c502013-04-05 13:47:09 +0000743/////////////////////////////////////////////////////////////////////
744
sugoi@google.com4775cba2013-04-17 13:46:56 +0000745void GrGLSimplexNoise::emitCode(GrGLShaderBuilder* builder,
746 const GrDrawEffect&,
747 EffectKey key,
748 const char* outputColor,
749 const char* inputColor,
750 const TextureSamplerArray&) {
751 sk_ignore_unused_variable(inputColor);
752
753 const char* vCoords;
754 fEffectMatrix.emitCodeMakeFSCoords2D(builder, key, &vCoords);
755
756 fSeedUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
757 kFloat_GrSLType, "seed");
758 const char* seedUni = builder->getUniformCStr(fSeedUni);
759 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
760 kMat33f_GrSLType, "invMatrix");
761 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
762 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
763 kVec2f_GrSLType, "baseFrequency");
764 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
765 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
766 kFloat_GrSLType, "alpha");
767 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
768
769 // Add vec3 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000770 static const GrGLShaderVar gVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000771 GrGLShaderVar("x", kVec3f_GrSLType)
772 };
773
774 SkString mod289_3_funcName;
775 builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kVec3f_GrSLType,
sugoi@google.comd537af52013-06-10 13:59:25 +0000776 "mod289", SK_ARRAY_COUNT(gVec3Args), gVec3Args,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000777 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
778 "return x - floor(x * C.xxx) * C.yyy;", &mod289_3_funcName);
779
780 // Add vec4 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000781 static const GrGLShaderVar gVec4Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000782 GrGLShaderVar("x", kVec4f_GrSLType)
783 };
784
785 SkString mod289_4_funcName;
786 builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kVec4f_GrSLType,
sugoi@google.comd537af52013-06-10 13:59:25 +0000787 "mod289", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000788 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
789 "return x - floor(x * C.xxxx) * C.yyyy;", &mod289_4_funcName);
790
791 // Add vec4 permute function
sugoi@google.comd537af52013-06-10 13:59:25 +0000792 SkString permuteCode;
793 permuteCode.appendf("const vec2 C = vec2(34.0, 1.0);\n"
794 "return %s(((x * C.xxxx) + C.yyyy) * x);", mod289_4_funcName.c_str());
795 SkString permuteFuncName;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000796 builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kVec4f_GrSLType,
sugoi@google.comd537af52013-06-10 13:59:25 +0000797 "permute", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
798 permuteCode.c_str(), &permuteFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000799
800 // Add vec4 taylorInvSqrt function
sugoi@google.comd537af52013-06-10 13:59:25 +0000801 SkString taylorInvSqrtFuncName;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000802 builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kVec4f_GrSLType,
sugoi@google.comd537af52013-06-10 13:59:25 +0000803 "taylorInvSqrt", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000804 "const vec2 C = vec2(-0.85373472095314, 1.79284291400159);\n"
sugoi@google.comd537af52013-06-10 13:59:25 +0000805 "return x * C.xxxx + C.yyyy;", &taylorInvSqrtFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000806
807 // Add vec3 noise function
sugoi@google.comd537af52013-06-10 13:59:25 +0000808 static const GrGLShaderVar gNoiseVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000809 GrGLShaderVar("v", kVec3f_GrSLType)
810 };
811
sugoi@google.comd537af52013-06-10 13:59:25 +0000812 SkString noiseCode;
813 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000814 "const vec2 C = vec2(1.0/6.0, 1.0/3.0);\n"
815 "const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n"
816
817 // First corner
818 "vec3 i = floor(v + dot(v, C.yyy));\n"
819 "vec3 x0 = v - i + dot(i, C.xxx);\n"
820
821 // Other corners
822 "vec3 g = step(x0.yzx, x0.xyz);\n"
823 "vec3 l = 1.0 - g;\n"
824 "vec3 i1 = min(g.xyz, l.zxy);\n"
825 "vec3 i2 = max(g.xyz, l.zxy);\n"
826
827 "vec3 x1 = x0 - i1 + C.xxx;\n"
828 "vec3 x2 = x0 - i2 + C.yyy;\n" // 2.0*C.x = 1/3 = C.y
829 "vec3 x3 = x0 - D.yyy;\n" // -1.0+3.0*C.x = -0.5 = -D.y
830 );
831
sugoi@google.comd537af52013-06-10 13:59:25 +0000832 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000833 // Permutations
834 "i = %s(i);\n"
835 "vec4 p = %s(%s(%s(\n"
836 " i.z + vec4(0.0, i1.z, i2.z, 1.0)) +\n"
837 " i.y + vec4(0.0, i1.y, i2.y, 1.0)) +\n"
838 " i.x + vec4(0.0, i1.x, i2.x, 1.0));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000839 mod289_3_funcName.c_str(), permuteFuncName.c_str(), permuteFuncName.c_str(),
840 permuteFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000841
sugoi@google.comd537af52013-06-10 13:59:25 +0000842 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000843 // Gradients: 7x7 points over a square, mapped onto an octahedron.
844 // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
845 "float n_ = 0.142857142857;\n" // 1.0/7.0
846 "vec3 ns = n_ * D.wyz - D.xzx;\n"
847
848 "vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\n" // mod(p,7*7)
849
850 "vec4 x_ = floor(j * ns.z);\n"
851 "vec4 y_ = floor(j - 7.0 * x_);" // mod(j,N)
852
853 "vec4 x = x_ *ns.x + ns.yyyy;\n"
854 "vec4 y = y_ *ns.x + ns.yyyy;\n"
855 "vec4 h = 1.0 - abs(x) - abs(y);\n"
856
857 "vec4 b0 = vec4(x.xy, y.xy);\n"
858 "vec4 b1 = vec4(x.zw, y.zw);\n"
859 );
860
sugoi@google.comd537af52013-06-10 13:59:25 +0000861 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000862 "vec4 s0 = floor(b0) * 2.0 + 1.0;\n"
863 "vec4 s1 = floor(b1) * 2.0 + 1.0;\n"
864 "vec4 sh = -step(h, vec4(0.0));\n"
865
866 "vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;\n"
867 "vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;\n"
868
869 "vec3 p0 = vec3(a0.xy, h.x);\n"
870 "vec3 p1 = vec3(a0.zw, h.y);\n"
871 "vec3 p2 = vec3(a1.xy, h.z);\n"
872 "vec3 p3 = vec3(a1.zw, h.w);\n"
873 );
874
sugoi@google.comd537af52013-06-10 13:59:25 +0000875 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000876 // Normalise gradients
877 "vec4 norm = %s(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n"
878 "p0 *= norm.x;\n"
879 "p1 *= norm.y;\n"
880 "p2 *= norm.z;\n"
881 "p3 *= norm.w;\n"
882
883 // Mix final noise value
884 "vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n"
885 "m = m * m;\n"
886 "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 +0000887 taylorInvSqrtFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000888
sugoi@google.comd537af52013-06-10 13:59:25 +0000889 SkString noiseFuncName;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000890 builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kFloat_GrSLType,
sugoi@google.comd537af52013-06-10 13:59:25 +0000891 "snoise", SK_ARRAY_COUNT(gNoiseVec3Args), gNoiseVec3Args,
892 noiseCode.c_str(), &noiseFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000893
894 const char* noiseVecIni = "noiseVecIni";
895 const char* factors = "factors";
896 const char* sum = "sum";
897 const char* xOffsets = "xOffsets";
898 const char* yOffsets = "yOffsets";
899 const char* channel = "channel";
900
901 // Fill with some prime numbers
902 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(13.0, 53.0, 101.0, 151.0);\n", xOffsets);
903 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(109.0, 167.0, 23.0, 67.0);\n", yOffsets);
904
905 // There are rounding errors if the floor operation is not performed here
906 builder->fsCodeAppendf(
907 "\t\tvec3 %s = vec3(floor((%s*vec3(%s, 1.0)).xy) * vec2(0.66) * %s, 0.0);\n",
908 noiseVecIni, invMatrixUni, vCoords, baseFrequencyUni);
909
910 // Perturb the texcoords with three components of noise
911 builder->fsCodeAppendf("\t\t%s += 0.1 * vec3(%s(%s + vec3( 0.0, 0.0, %s)),"
912 "%s(%s + vec3( 43.0, 17.0, %s)),"
913 "%s(%s + vec3(-17.0, -43.0, %s)));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000914 noiseVecIni, noiseFuncName.c_str(), noiseVecIni, seedUni,
915 noiseFuncName.c_str(), noiseVecIni, seedUni,
916 noiseFuncName.c_str(), noiseVecIni, seedUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000917
918 builder->fsCodeAppendf("\t\t%s = vec4(0.0);\n", outputColor);
919
920 builder->fsCodeAppendf("\t\tvec3 %s = vec3(1.0);\n", factors);
921 builder->fsCodeAppendf("\t\tfloat %s = 0.0;\n", sum);
922
923 // Loop over all octaves
924 builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {\n", fNumOctaves);
925
926 // Loop over the 4 channels
927 builder->fsCodeAppendf("\t\t\tfor (int %s = 3; %s >= 0; --%s) {\n", channel, channel, channel);
928
929 builder->fsCodeAppendf(
930 "\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 +0000931 outputColor, factors, noiseFuncName.c_str(), noiseVecIni, factors, xOffsets, channel,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000932 yOffsets, channel, seedUni, factors);
933
934 builder->fsCodeAppend("\t\t\t}\n"); // end of the for loop on channels
935
936 builder->fsCodeAppendf("\t\t\t%s += %s.x;\n", sum, factors);
937 builder->fsCodeAppendf("\t\t\t%s *= vec3(0.5, 2.0, 0.75);\n", factors);
938
939 builder->fsCodeAppend("\t\t}\n"); // end of the for loop on octaves
940
941 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
942 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
943 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
944 builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5 / %s) + vec4(0.5);\n",
945 outputColor, outputColor, sum);
946 } else {
947 builder->fsCodeAppendf("\t\t%s = abs(%s / vec4(%s));\n",
948 outputColor, outputColor, sum);
949 }
950
951 builder->fsCodeAppendf("\t\t%s.a *= %s;\n", outputColor, alphaUni);
952
953 // Clamp values
954 builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);\n", outputColor, outputColor);
955
956 // Pre-multiply the result
957 builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
958 outputColor, outputColor, outputColor, outputColor);
959}
960
sugoi@google.come3b4c502013-04-05 13:47:09 +0000961void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder,
962 const GrDrawEffect&,
963 EffectKey key,
964 const char* outputColor,
965 const char* inputColor,
966 const TextureSamplerArray& samplers) {
967 sk_ignore_unused_variable(inputColor);
968
969 const char* vCoords;
970 fEffectMatrix.emitCodeMakeFSCoords2D(builder, key, &vCoords);
971
972 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
973 kMat33f_GrSLType, "invMatrix");
974 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
975 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
976 kVec2f_GrSLType, "baseFrequency");
977 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
978 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
979 kFloat_GrSLType, "alpha");
980 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
981
982 const char* stitchDataUni = NULL;
983 if (fStitchTiles) {
984 fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
985 kVec4f_GrSLType, "stitchData");
986 stitchDataUni = builder->getUniformCStr(fStitchDataUni);
987 }
988
sugoi@google.comd537af52013-06-10 13:59:25 +0000989 // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
990 const char* chanCoordR = "0.125";
991 const char* chanCoordG = "0.375";
992 const char* chanCoordB = "0.625";
993 const char* chanCoordA = "0.875";
994 const char* chanCoord = "chanCoord";
sugoi@google.come3b4c502013-04-05 13:47:09 +0000995 const char* stitchData = "stitchData";
996 const char* ratio = "ratio";
sugoi@google.come3b4c502013-04-05 13:47:09 +0000997 const char* noiseXY = "noiseXY";
998 const char* noiseVec = "noiseVec";
sugoi@google.come3b4c502013-04-05 13:47:09 +0000999 const char* noiseSmooth = "noiseSmooth";
1000 const char* fractVal = "fractVal";
1001 const char* uv = "uv";
1002 const char* ab = "ab";
1003 const char* latticeIdx = "latticeIdx";
1004 const char* lattice = "lattice";
1005 const char* perlinNoise = "4096.0";
1006 const char* inc8bit = "0.00390625"; // 1.0 / 256.0
1007 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
1008 // [-1,1] vector and perform a dot product between that vector and the provided vector.
1009 const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
1010
sugoi@google.comd537af52013-06-10 13:59:25 +00001011 // Add noise function
1012 static const GrGLShaderVar gPerlinNoiseArgs[] = {
1013 GrGLShaderVar(chanCoord, kFloat_GrSLType),
1014 GrGLShaderVar(noiseVec, kVec2f_GrSLType)
1015 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001016
sugoi@google.comd537af52013-06-10 13:59:25 +00001017 static const GrGLShaderVar gPerlinNoiseStitchArgs[] = {
1018 GrGLShaderVar(chanCoord, kFloat_GrSLType),
1019 GrGLShaderVar(noiseVec, kVec2f_GrSLType),
1020 GrGLShaderVar(stitchData, kVec4f_GrSLType)
1021 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001022
sugoi@google.comd537af52013-06-10 13:59:25 +00001023 SkString noiseCode;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001024
sugoi@google.comd537af52013-06-10 13:59:25 +00001025 noiseCode.appendf(
1026 "\tvec4 %s = vec4(floor(%s) + vec2(%s), fract(%s));",
1027 noiseXY, noiseVec, perlinNoise, noiseVec);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001028
1029 // smooth curve : t * t * (3 - 2 * t)
sugoi@google.comd537af52013-06-10 13:59:25 +00001030 noiseCode.appendf("\n\tvec2 %s = %s.zw * %s.zw * (vec2(3.0) - vec2(2.0) * %s.zw);",
1031 noiseSmooth, noiseXY, noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001032
1033 // Adjust frequencies if we're stitching tiles
1034 if (fStitchTiles) {
sugoi@google.comd537af52013-06-10 13:59:25 +00001035 noiseCode.appendf("\n\tif(%s.x >= %s.y) { %s.x -= %s.x; }",
1036 noiseXY, stitchData, noiseXY, stitchData);
1037 noiseCode.appendf("\n\tif(%s.x >= (%s.y - 1.0)) { %s.x -= (%s.x - 1.0); }",
1038 noiseXY, stitchData, noiseXY, stitchData);
1039 noiseCode.appendf("\n\tif(%s.y >= %s.w) { %s.y -= %s.z; }",
1040 noiseXY, stitchData, noiseXY, stitchData);
1041 noiseCode.appendf("\n\tif(%s.y >= (%s.w - 1.0)) { %s.y -= (%s.z - 1.0); }",
1042 noiseXY, stitchData, noiseXY, stitchData);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001043 }
1044
1045 // Get texture coordinates and normalize
sugoi@google.comd537af52013-06-10 13:59:25 +00001046 noiseCode.appendf("\n\t%s.xy = fract(floor(mod(%s.xy, 256.0)) / vec2(256.0));\n",
1047 noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001048
1049 // Get permutation for x
1050 {
1051 SkString xCoords("");
1052 xCoords.appendf("vec2(%s.x, 0.5)", noiseXY);
1053
sugoi@google.comd537af52013-06-10 13:59:25 +00001054 noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
1055 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1056 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001057 }
1058
1059 // Get permutation for x + 1
1060 {
1061 SkString xCoords("");
1062 xCoords.appendf("vec2(fract(%s.x + %s), 0.5)", noiseXY, inc8bit);
1063
sugoi@google.comd537af52013-06-10 13:59:25 +00001064 noiseCode.appendf("\n\t%s.y = ", latticeIdx);
1065 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1066 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001067 }
1068
1069 // Get (x,y) coordinates with the permutated x
sugoi@google.comd537af52013-06-10 13:59:25 +00001070 noiseCode.appendf("\n\t%s = fract(%s + %s.yy);", latticeIdx, latticeIdx, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001071
sugoi@google.comd537af52013-06-10 13:59:25 +00001072 noiseCode.appendf("\n\tvec2 %s = %s.zw;", fractVal, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001073
sugoi@google.comd537af52013-06-10 13:59:25 +00001074 noiseCode.appendf("\n\n\tvec2 %s;", uv);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001075 // Compute u, at offset (0,0)
1076 {
1077 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001078 latticeCoords.appendf("vec2(%s.x, %s)", latticeIdx, chanCoord);
1079 noiseCode.appendf("\n\tvec4 %s = ", lattice);
1080 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1081 kVec2f_GrSLType);
1082 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1083 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001084 }
1085
sugoi@google.comd537af52013-06-10 13:59:25 +00001086 noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001087 // Compute v, at offset (-1,0)
1088 {
1089 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001090 latticeCoords.appendf("vec2(%s.y, %s)", latticeIdx, chanCoord);
1091 noiseCode.append("lattice = ");
1092 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
1098 // Compute 'a' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001099 noiseCode.appendf("\n\tvec2 %s;", ab);
1100 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 +00001101
sugoi@google.comd537af52013-06-10 13:59:25 +00001102 noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001103 // Compute v, at offset (-1,-1)
1104 {
1105 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001106 latticeCoords.appendf("vec2(fract(%s.y + %s), %s)", latticeIdx, inc8bit, chanCoord);
1107 noiseCode.append("lattice = ");
1108 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1109 kVec2f_GrSLType);
1110 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1111 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001112 }
1113
sugoi@google.comd537af52013-06-10 13:59:25 +00001114 noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001115 // Compute u, at offset (0,-1)
1116 {
1117 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001118 latticeCoords.appendf("vec2(fract(%s.x + %s), %s)", latticeIdx, inc8bit, chanCoord);
1119 noiseCode.append("lattice = ");
1120 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1121 kVec2f_GrSLType);
1122 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1123 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001124 }
1125
1126 // Compute 'b' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001127 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 +00001128 // Compute the noise as a linear interpolation of 'a' and 'b'
sugoi@google.comd537af52013-06-10 13:59:25 +00001129 noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001130
sugoi@google.comd537af52013-06-10 13:59:25 +00001131 SkString noiseFuncName;
1132 if (fStitchTiles) {
1133 builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kFloat_GrSLType, "perlinnoise",
1134 SK_ARRAY_COUNT(gPerlinNoiseStitchArgs), gPerlinNoiseStitchArgs,
1135 noiseCode.c_str(), &noiseFuncName);
1136 } else {
1137 builder->emitFunction(GrGLShaderBuilder::kFragment_ShaderType, kFloat_GrSLType, "perlinnoise",
1138 SK_ARRAY_COUNT(gPerlinNoiseArgs), gPerlinNoiseArgs,
1139 noiseCode.c_str(), &noiseFuncName);
1140 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001141
sugoi@google.comd537af52013-06-10 13:59:25 +00001142 // There are rounding errors if the floor operation is not performed here
1143 builder->fsCodeAppendf("\n\t\tvec2 %s = floor((%s * vec3(%s, 1.0)).xy) * %s;",
1144 noiseVec, invMatrixUni, vCoords, baseFrequencyUni);
1145
1146 // Clear the color accumulator
1147 builder->fsCodeAppendf("\n\t\t%s = vec4(0.0);", outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001148
1149 if (fStitchTiles) {
sugoi@google.comd537af52013-06-10 13:59:25 +00001150 // Set up TurbulenceInitial stitch values.
1151 builder->fsCodeAppendf("\n\t\tvec4 %s = %s;", stitchData, stitchDataUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001152 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001153
sugoi@google.comd537af52013-06-10 13:59:25 +00001154 builder->fsCodeAppendf("\n\t\tfloat %s = 1.0;", ratio);
1155
1156 // Loop over all octaves
1157 builder->fsCodeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
1158
1159 builder->fsCodeAppendf("\n\t\t\t%s += ", outputColor);
1160 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1161 builder->fsCodeAppend("abs(");
1162 }
1163 if (fStitchTiles) {
1164 builder->fsCodeAppendf(
1165 "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
1166 "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
1167 noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
1168 noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
1169 noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
1170 noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
1171 } else {
1172 builder->fsCodeAppendf(
1173 "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
1174 "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
1175 noiseFuncName.c_str(), chanCoordR, noiseVec,
1176 noiseFuncName.c_str(), chanCoordG, noiseVec,
1177 noiseFuncName.c_str(), chanCoordB, noiseVec,
1178 noiseFuncName.c_str(), chanCoordA, noiseVec);
1179 }
1180 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1181 builder->fsCodeAppendf(")"); // end of "abs("
1182 }
1183 builder->fsCodeAppendf(" * %s;", ratio);
1184
1185 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
1186 builder->fsCodeAppendf("\n\t\t\t%s *= 0.5;", ratio);
1187
1188 if (fStitchTiles) {
1189 builder->fsCodeAppendf("\n\t\t\t%s.xz *= vec2(2.0);", stitchData);
1190 builder->fsCodeAppendf("\n\t\t\t%s.yw = %s.xz + vec2(%s);", stitchData, stitchData, perlinNoise);
1191 }
1192 builder->fsCodeAppend("\n\t\t}"); // end of the for loop on octaves
sugoi@google.come3b4c502013-04-05 13:47:09 +00001193
1194 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
1195 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
1196 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
sugoi@google.comd537af52013-06-10 13:59:25 +00001197 builder->fsCodeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001198 }
1199
sugoi@google.comd537af52013-06-10 13:59:25 +00001200 builder->fsCodeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001201
1202 // Clamp values
sugoi@google.comd537af52013-06-10 13:59:25 +00001203 builder->fsCodeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001204
1205 // Pre-multiply the result
sugoi@google.comd537af52013-06-10 13:59:25 +00001206 builder->fsCodeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
sugoi@google.come3b4c502013-04-05 13:47:09 +00001207 outputColor, outputColor, outputColor, outputColor);
1208}
1209
sugoi@google.com4775cba2013-04-17 13:46:56 +00001210GrGLNoise::GrGLNoise(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect)
sugoi@google.come3b4c502013-04-05 13:47:09 +00001211 : INHERITED (factory)
1212 , fType(drawEffect.castEffect<GrPerlinNoiseEffect>().type())
1213 , fStitchTiles(drawEffect.castEffect<GrPerlinNoiseEffect>().stitchTiles())
1214 , fNumOctaves(drawEffect.castEffect<GrPerlinNoiseEffect>().numOctaves())
1215 , fEffectMatrix(drawEffect.castEffect<GrPerlinNoiseEffect>().coordsType()) {
1216}
1217
sugoi@google.com4775cba2013-04-17 13:46:56 +00001218GrGLEffect::EffectKey GrGLNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001219 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1220
1221 EffectKey key = turbulence.numOctaves();
1222
1223 key = key << 3; // Make room for next 3 bits
1224
1225 switch (turbulence.type()) {
1226 case SkPerlinNoiseShader::kFractalNoise_Type:
1227 key |= 0x1;
1228 break;
1229 case SkPerlinNoiseShader::kTurbulence_Type:
1230 key |= 0x2;
1231 break;
1232 default:
1233 // leave key at 0
1234 break;
1235 }
1236
1237 if (turbulence.stitchTiles()) {
1238 key |= 0x4; // Flip the 3rd bit if tile stitching is on
1239 }
1240
1241 key = key << GrGLEffectMatrix::kKeyBits;
1242
1243 SkMatrix m = turbulence.matrix();
1244 m.postTranslate(SK_Scalar1, SK_Scalar1);
1245 return key | GrGLEffectMatrix::GenKey(m, drawEffect,
1246 drawEffect.castEffect<GrPerlinNoiseEffect>().coordsType(), NULL);
1247}
1248
sugoi@google.com4775cba2013-04-17 13:46:56 +00001249void GrGLNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001250 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1251
1252 const SkVector& baseFrequency = turbulence.baseFrequency();
1253 uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001254 uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
1255
1256 SkMatrix m = turbulence.matrix();
1257 SkMatrix invM;
1258 if (!m.invert(&invM)) {
1259 invM.reset();
1260 } else {
1261 invM.postConcat(invM); // Square the matrix
1262 }
1263 uman.setSkMatrix(fInvMatrixUni, invM);
1264
1265 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
1266 // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions.
1267 m.postTranslate(SK_Scalar1, SK_Scalar1);
1268 fEffectMatrix.setData(uman, m, drawEffect, NULL);
1269}
1270
sugoi@google.com4775cba2013-04-17 13:46:56 +00001271void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1272 INHERITED::setData(uman, drawEffect);
1273
1274 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1275 if (turbulence.stitchTiles()) {
1276 const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
1277 uman.set4f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
1278 SkIntToScalar(stitchData.fWrapX),
1279 SkIntToScalar(stitchData.fHeight),
1280 SkIntToScalar(stitchData.fWrapY));
1281 }
1282}
1283
1284void GrGLSimplexNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1285 INHERITED::setData(uman, drawEffect);
1286
1287 const GrSimplexNoiseEffect& turbulence = drawEffect.castEffect<GrSimplexNoiseEffect>();
1288 uman.set1f(fSeedUni, turbulence.seed());
1289}
1290
sugoi@google.come3b4c502013-04-05 13:47:09 +00001291/////////////////////////////////////////////////////////////////////
1292
1293GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001294 SkASSERT(NULL != context);
1295
1296 // Either we don't stitch tiles, either we have a valid tile size
1297 SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
1298
sugoi@google.com4775cba2013-04-17 13:46:56 +00001299#ifdef SK_USE_SIMPLEX_NOISE
1300 // Simplex noise is currently disabled but can be enabled by defining SK_USE_SIMPLEX_NOISE
1301 sk_ignore_unused_variable(context);
1302 GrEffectRef* effect =
1303 GrSimplexNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
1304 fNumOctaves, fStitchTiles, fSeed,
1305 this->getLocalMatrix(), paint.getAlpha());
1306#else
sugoi@google.come3b4c502013-04-05 13:47:09 +00001307 GrTexture* permutationsTexture = GrLockAndRefCachedBitmapTexture(
1308 context, *fPaintingData->getPermutationsBitmap(), NULL);
1309 GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture(
1310 context, *fPaintingData->getNoiseBitmap(), NULL);
1311
1312 GrEffectRef* effect = (NULL != permutationsTexture) && (NULL != noiseTexture) ?
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001313 GrPerlinNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001314 fNumOctaves, fStitchTiles,
1315 fPaintingData->fStitchDataInit,
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001316 permutationsTexture, noiseTexture,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001317 this->getLocalMatrix(), paint.getAlpha()) :
1318 NULL;
1319
1320 // Unlock immediately, this is not great, but we don't have a way of
1321 // knowing when else to unlock it currently. TODO: Remove this when
1322 // unref becomes the unlock replacement for all types of textures.
1323 if (NULL != permutationsTexture) {
1324 GrUnlockAndUnrefCachedBitmapTexture(permutationsTexture);
1325 }
1326 if (NULL != noiseTexture) {
1327 GrUnlockAndUnrefCachedBitmapTexture(noiseTexture);
1328 }
sugoi@google.com4775cba2013-04-17 13:46:56 +00001329#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +00001330
1331 return effect;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001332}
1333
1334#else
1335
1336GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext*, const SkPaint&) const {
sugoi@google.comd537af52013-06-10 13:59:25 +00001337#if !defined(SK_BUILD_FOR_ANDROID)
sugoi@google.come3b4c502013-04-05 13:47:09 +00001338 SkDEBUGFAIL("Should not call in GPU-less build");
sugoi@google.com0a1db4a2013-04-17 14:50:38 +00001339#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +00001340 return NULL;
1341}
1342
1343#endif
1344
1345#ifdef SK_DEVELOPER
1346void SkPerlinNoiseShader::toString(SkString* str) const {
1347 str->append("SkPerlinNoiseShader: (");
1348
1349 str->append("type: ");
1350 switch (fType) {
1351 case kFractalNoise_Type:
1352 str->append("\"fractal noise\"");
1353 break;
1354 case kTurbulence_Type:
1355 str->append("\"turbulence\"");
1356 break;
1357 default:
1358 str->append("\"unknown\"");
1359 break;
1360 }
1361 str->append(" base frequency: (");
1362 str->appendScalar(fBaseFrequencyX);
1363 str->append(", ");
1364 str->appendScalar(fBaseFrequencyY);
1365 str->append(") number of octaves: ");
1366 str->appendS32(fNumOctaves);
1367 str->append(" seed: ");
1368 str->appendScalar(fSeed);
1369 str->append(" stitch tiles: ");
1370 str->append(fStitchTiles ? "true " : "false ");
1371
1372 this->INHERITED::toString(str);
1373
1374 str->append(")");
1375}
1376#endif