2 * Copyright 2013 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
9 #include "SkPerlinNoiseShader.h"
10 #include "SkColorFilter.h"
11 #include "SkReadBuffer.h"
12 #include "SkWriteBuffer.h"
14 #include "SkUnPreMultiply.h"
18 #include "GrContext.h"
19 #include "GrCoordTransform.h"
20 #include "gl/GrGLEffect.h"
21 #include "GrTBackendEffectFactory.h"
25 static const int kBlockSize = 256;
26 static const int kBlockMask = kBlockSize - 1;
27 static const int kPerlinNoise = 4096;
28 static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
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)
35 inline 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;
42 if (noiseValue >= limitValue - 1) {
43 noiseValue -= newValue - 1;
48 inline SkScalar smoothCurve(SkScalar t) {
49 static const SkScalar SK_Scalar3 = 3.0f;
51 // returns t * t * (3 - 2 * t)
52 return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
55 bool perlin_noise_type_is_valid(SkPerlinNoiseShader::Type type) {
56 return (SkPerlinNoiseShader::kFractalNoise_Type == type) ||
57 (SkPerlinNoiseShader::kTurbulence_Type == type);
62 struct SkPerlinNoiseShader::StitchData {
70 bool operator==(const StitchData& other) const {
71 return fWidth == other.fWidth &&
72 fWrapX == other.fWrapX &&
73 fHeight == other.fHeight &&
74 fWrapY == other.fWrapY;
77 int fWidth; // How much to subtract to wrap for stitching.
78 int fWrapX; // Minimum value to wrap.
83 struct SkPerlinNoiseShader::PaintingData {
84 PaintingData(const SkISize& tileSize)
87 , fPermutationsBitmap(NULL)
93 SkDELETE(fPermutationsBitmap);
94 SkDELETE(fNoiseBitmap);
98 uint8_t fLatticeSelector[kBlockSize];
99 uint16_t fNoise[4][kBlockSize][2];
100 SkPoint fGradient[4][kBlockSize];
102 SkVector fBaseFrequency;
103 StitchData fStitchDataInit;
107 SkBitmap* fPermutationsBitmap;
108 SkBitmap* fNoiseBitmap;
112 inline int random() {
113 static const int gRandAmplitude = 16807; // 7**5; primitive root of m
114 static const int gRandQ = 127773; // m / a
115 static const int gRandR = 2836; // m % a
117 int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
119 result += kRandMaximum;
124 void init(SkScalar seed)
126 static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
128 // According to the SVG spec, we must truncate (not round) the seed value.
129 fSeed = SkScalarTruncToInt(seed);
130 // The seed value clamp to the range [1, kRandMaximum - 1].
132 fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
134 if (fSeed > kRandMaximum - 1) {
135 fSeed = kRandMaximum - 1;
137 for (int channel = 0; channel < 4; ++channel) {
138 for (int i = 0; i < kBlockSize; ++i) {
139 fLatticeSelector[i] = i;
140 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
141 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
144 for (int i = kBlockSize - 1; i > 0; --i) {
145 int k = fLatticeSelector[i];
146 int j = random() % kBlockSize;
148 SkASSERT(j < kBlockSize);
149 fLatticeSelector[i] = fLatticeSelector[j];
150 fLatticeSelector[j] = k;
153 // Perform the permutations now
156 uint16_t noise[4][kBlockSize][2];
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 noise[channel][i][j] = fNoise[channel][i][j];
164 // Do permutations on noise data
165 for (int i = 0; i < kBlockSize; ++i) {
166 for (int channel = 0; channel < 4; ++channel) {
167 for (int j = 0; j < 2; ++j) {
168 fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
174 // Half of the largest possible value for 16 bit unsigned int
175 static const SkScalar gHalfMax16bits = 32767.5f;
177 // Compute gradients from permutated noise data
178 for (int channel = 0; channel < 4; ++channel) {
179 for (int i = 0; i < kBlockSize; ++i) {
180 fGradient[channel][i] = SkPoint::Make(
181 SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
183 SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
185 fGradient[channel][i].normalize();
186 // Put the normalized gradient back into the noise data
187 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
188 fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
189 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
190 fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
194 // Invalidate bitmaps
195 SkDELETE(fPermutationsBitmap);
196 fPermutationsBitmap = NULL;
197 SkDELETE(fNoiseBitmap);
202 SkScalar tileWidth = SkIntToScalar(fTileSize.width());
203 SkScalar tileHeight = SkIntToScalar(fTileSize.height());
204 SkASSERT(tileWidth > 0 && tileHeight > 0);
205 // When stitching tiled turbulence, the frequencies must be adjusted
206 // so that the tile borders will be continuous.
207 if (fBaseFrequency.fX) {
208 SkScalar lowFrequencx =
209 SkScalarFloorToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
210 SkScalar highFrequencx =
211 SkScalarCeilToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
212 // BaseFrequency should be non-negative according to the standard.
213 if (SkScalarDiv(fBaseFrequency.fX, lowFrequencx) <
214 SkScalarDiv(highFrequencx, fBaseFrequency.fX)) {
215 fBaseFrequency.fX = lowFrequencx;
217 fBaseFrequency.fX = highFrequencx;
220 if (fBaseFrequency.fY) {
221 SkScalar lowFrequency =
222 SkScalarFloorToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
223 SkScalar highFrequency =
224 SkScalarCeilToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
225 if (SkScalarDiv(fBaseFrequency.fY, lowFrequency) <
226 SkScalarDiv(highFrequency, fBaseFrequency.fY)) {
227 fBaseFrequency.fY = lowFrequency;
229 fBaseFrequency.fY = highFrequency;
232 // Set up TurbulenceInitial stitch values.
233 fStitchDataInit.fWidth =
234 SkScalarRoundToInt(tileWidth * fBaseFrequency.fX);
235 fStitchDataInit.fWrapX = kPerlinNoise + fStitchDataInit.fWidth;
236 fStitchDataInit.fHeight =
237 SkScalarRoundToInt(tileHeight * fBaseFrequency.fY);
238 fStitchDataInit.fWrapY = kPerlinNoise + fStitchDataInit.fHeight;
241 SkBitmap* getPermutationsBitmap()
243 if (!fPermutationsBitmap) {
244 fPermutationsBitmap = SkNEW(SkBitmap);
245 fPermutationsBitmap->allocPixels(SkImageInfo::MakeA8(kBlockSize, 1));
246 uint8_t* bitmapPixels = fPermutationsBitmap->getAddr8(0, 0);
247 memcpy(bitmapPixels, fLatticeSelector, sizeof(uint8_t) * kBlockSize);
249 return fPermutationsBitmap;
252 SkBitmap* getNoiseBitmap()
255 fNoiseBitmap = SkNEW(SkBitmap);
256 fNoiseBitmap->allocPixels(SkImageInfo::MakeN32Premul(kBlockSize, 4));
257 uint32_t* bitmapPixels = fNoiseBitmap->getAddr32(0, 0);
258 memcpy(bitmapPixels, fNoise[0][0], sizeof(uint16_t) * kBlockSize * 4 * 2);
264 SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
265 int numOctaves, SkScalar seed,
266 const SkISize* tileSize) {
267 return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY,
268 numOctaves, seed, tileSize));
271 SkShader* SkPerlinNoiseShader::CreateTubulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
272 int numOctaves, SkScalar seed,
273 const SkISize* tileSize) {
274 return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY,
275 numOctaves, seed, tileSize));
278 SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
279 SkScalar baseFrequencyX,
280 SkScalar baseFrequencyY,
283 const SkISize* tileSize)
285 , fBaseFrequencyX(baseFrequencyX)
286 , fBaseFrequencyY(baseFrequencyY)
287 , fNumOctaves(numOctaves > 255 ? 255 : numOctaves/*[0,255] octaves allowed*/)
289 , fStitchTiles((tileSize != NULL) && !tileSize->isEmpty())
290 , fPaintingData(NULL)
292 SkASSERT(numOctaves >= 0 && numOctaves < 256);
293 setTileSize(fStitchTiles ? *tileSize : SkISize::Make(0,0));
297 SkPerlinNoiseShader::SkPerlinNoiseShader(SkReadBuffer& buffer) :
298 INHERITED(buffer), fPaintingData(NULL) {
299 fType = (SkPerlinNoiseShader::Type) buffer.readInt();
300 fBaseFrequencyX = buffer.readScalar();
301 fBaseFrequencyY = buffer.readScalar();
302 fNumOctaves = buffer.readInt();
303 fSeed = buffer.readScalar();
304 fStitchTiles = buffer.readBool();
305 fTileSize.fWidth = buffer.readInt();
306 fTileSize.fHeight = buffer.readInt();
307 setTileSize(fTileSize);
309 buffer.validate(perlin_noise_type_is_valid(fType) &&
310 (fNumOctaves >= 0) && (fNumOctaves <= 255));
313 SkPerlinNoiseShader::~SkPerlinNoiseShader() {
314 // Safety, should have been done in endContext()
315 SkDELETE(fPaintingData);
318 void SkPerlinNoiseShader::flatten(SkWriteBuffer& buffer) const {
319 this->INHERITED::flatten(buffer);
320 buffer.writeInt((int) fType);
321 buffer.writeScalar(fBaseFrequencyX);
322 buffer.writeScalar(fBaseFrequencyY);
323 buffer.writeInt(fNumOctaves);
324 buffer.writeScalar(fSeed);
325 buffer.writeBool(fStitchTiles);
326 buffer.writeInt(fTileSize.fWidth);
327 buffer.writeInt(fTileSize.fHeight);
330 void SkPerlinNoiseShader::initPaint(PaintingData& paintingData)
332 paintingData.init(fSeed);
334 // Set frequencies to original values
335 paintingData.fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
336 // Adjust frequecies based on size if stitching is enabled
338 paintingData.stitch();
342 void SkPerlinNoiseShader::setTileSize(const SkISize& tileSize) {
343 fTileSize = tileSize;
345 if (NULL == fPaintingData) {
346 fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize));
347 initPaint(*fPaintingData);
350 fPaintingData->fTileSize = fTileSize;
351 // Set frequencies to original values
352 fPaintingData->fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
353 // Adjust frequecies based on size if stitching is enabled
355 fPaintingData->stitch();
360 SkScalar SkPerlinNoiseShader::noise2D(int channel, const PaintingData& paintingData,
361 const StitchData& stitchData, const SkPoint& noiseVector)
364 int noisePositionIntegerValue;
365 SkScalar noisePositionFractionValue;
366 Noise(SkScalar component)
368 SkScalar position = component + kPerlinNoise;
369 noisePositionIntegerValue = SkScalarFloorToInt(position);
370 noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
373 Noise noiseX(noiseVector.x());
374 Noise noiseY(noiseVector.y());
376 // If stitching, adjust lattice points accordingly.
378 noiseX.noisePositionIntegerValue =
379 checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
380 noiseY.noisePositionIntegerValue =
381 checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
383 noiseX.noisePositionIntegerValue &= kBlockMask;
384 noiseY.noisePositionIntegerValue &= kBlockMask;
386 paintingData.fLatticeSelector[noiseX.noisePositionIntegerValue] +
387 noiseY.noisePositionIntegerValue;
388 int nextLatticeIndex =
389 paintingData.fLatticeSelector[(noiseX.noisePositionIntegerValue + 1) & kBlockMask] +
390 noiseY.noisePositionIntegerValue;
391 SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
392 SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
393 // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
394 SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
395 noiseY.noisePositionFractionValue); // Offset (0,0)
396 u = paintingData.fGradient[channel][latticeIndex & kBlockMask].dot(fractionValue);
397 fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
398 v = paintingData.fGradient[channel][nextLatticeIndex & kBlockMask].dot(fractionValue);
399 SkScalar a = SkScalarInterp(u, v, sx);
400 fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
401 v = paintingData.fGradient[channel][(nextLatticeIndex + 1) & kBlockMask].dot(fractionValue);
402 fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
403 u = paintingData.fGradient[channel][(latticeIndex + 1) & kBlockMask].dot(fractionValue);
404 SkScalar b = SkScalarInterp(u, v, sx);
405 return SkScalarInterp(a, b, sy);
408 SkScalar SkPerlinNoiseShader::calculateTurbulenceValueForPoint(
409 int channel, const PaintingData& paintingData, StitchData& stitchData, const SkPoint& point)
412 // Set up TurbulenceInitial stitch values.
413 stitchData = paintingData.fStitchDataInit;
415 SkScalar turbulenceFunctionResult = 0;
416 SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), paintingData.fBaseFrequency.fX),
417 SkScalarMul(point.y(), paintingData.fBaseFrequency.fY)));
418 SkScalar ratio = SK_Scalar1;
419 for (int octave = 0; octave < fNumOctaves; ++octave) {
420 SkScalar noise = noise2D(channel, paintingData, stitchData, noiseVector);
421 turbulenceFunctionResult += SkScalarDiv(
422 (fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio);
427 // Update stitch values
428 stitchData.fWidth *= 2;
429 stitchData.fWrapX = stitchData.fWidth + kPerlinNoise;
430 stitchData.fHeight *= 2;
431 stitchData.fWrapY = stitchData.fHeight + kPerlinNoise;
435 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
436 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
437 if (fType == kFractalNoise_Type) {
438 turbulenceFunctionResult =
439 SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
442 if (channel == 3) { // Scale alpha by paint value
443 turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult,
444 SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255)));
448 return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
451 SkPMColor SkPerlinNoiseShader::shade(const SkPoint& point, StitchData& stitchData) {
452 SkMatrix matrix = fMatrix;
454 if (!matrix.invert(&invMatrix)) {
457 invMatrix.postConcat(invMatrix); // Square the matrix
459 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
460 // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
461 matrix.postTranslate(SK_Scalar1, SK_Scalar1);
463 matrix.mapPoints(&newPoint, &point, 1);
464 invMatrix.mapPoints(&newPoint, &newPoint, 1);
465 newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
466 newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
469 for (int channel = 3; channel >= 0; --channel) {
470 rgba[channel] = SkScalarFloorToInt(255 *
471 calculateTurbulenceValueForPoint(channel, *fPaintingData, stitchData, newPoint));
473 return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
476 bool SkPerlinNoiseShader::setContext(const SkBitmap& device, const SkPaint& paint,
477 const SkMatrix& matrix) {
479 return INHERITED::setContext(device, paint, matrix);
482 void SkPerlinNoiseShader::shadeSpan(int x, int y, SkPMColor result[], int count) {
483 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
484 StitchData stitchData;
485 for (int i = 0; i < count; ++i) {
486 result[i] = shade(point, stitchData);
487 point.fX += SK_Scalar1;
491 void SkPerlinNoiseShader::shadeSpan16(int x, int y, uint16_t result[], int count) {
492 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
493 StitchData stitchData;
495 for (int i = 0; i < count; ++i) {
496 unsigned dither = DITHER_VALUE(x);
497 result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
499 point.fX += SK_Scalar1;
503 /////////////////////////////////////////////////////////////////////
507 #include "GrTBackendEffectFactory.h"
509 class GrGLNoise : public GrGLEffect {
511 GrGLNoise(const GrBackendEffectFactory& factory,
512 const GrDrawEffect& drawEffect);
513 virtual ~GrGLNoise() {}
515 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
517 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
520 SkPerlinNoiseShader::Type fType;
523 GrGLUniformManager::UniformHandle fBaseFrequencyUni;
524 GrGLUniformManager::UniformHandle fAlphaUni;
525 GrGLUniformManager::UniformHandle fInvMatrixUni;
528 typedef GrGLEffect INHERITED;
531 class GrGLPerlinNoise : public GrGLNoise {
533 GrGLPerlinNoise(const GrBackendEffectFactory& factory,
534 const GrDrawEffect& drawEffect)
535 : GrGLNoise(factory, drawEffect) {}
536 virtual ~GrGLPerlinNoise() {}
538 virtual void emitCode(GrGLShaderBuilder*,
541 const char* outputColor,
542 const char* inputColor,
543 const TransformedCoordsArray&,
544 const TextureSamplerArray&) SK_OVERRIDE;
546 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
549 GrGLUniformManager::UniformHandle fStitchDataUni;
551 typedef GrGLNoise INHERITED;
554 class GrGLSimplexNoise : public GrGLNoise {
555 // Note : This is for reference only. GrGLPerlinNoise is used for processing.
557 GrGLSimplexNoise(const GrBackendEffectFactory& factory,
558 const GrDrawEffect& drawEffect)
559 : GrGLNoise(factory, drawEffect) {}
561 virtual ~GrGLSimplexNoise() {}
563 virtual void emitCode(GrGLShaderBuilder*,
566 const char* outputColor,
567 const char* inputColor,
568 const TransformedCoordsArray&,
569 const TextureSamplerArray&) SK_OVERRIDE;
571 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
574 GrGLUniformManager::UniformHandle fSeedUni;
576 typedef GrGLNoise INHERITED;
579 /////////////////////////////////////////////////////////////////////
581 class GrNoiseEffect : public GrEffect {
583 virtual ~GrNoiseEffect() { }
585 SkPerlinNoiseShader::Type type() const { return fType; }
586 bool stitchTiles() const { return fStitchTiles; }
587 const SkVector& baseFrequency() const { return fBaseFrequency; }
588 int numOctaves() const { return fNumOctaves; }
589 const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
590 uint8_t alpha() const { return fAlpha; }
592 void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE {
593 *validFlags = 0; // This is noise. Nothing is constant.
597 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
598 const GrNoiseEffect& s = CastEffect<GrNoiseEffect>(sBase);
599 return fType == s.fType &&
600 fBaseFrequency == s.fBaseFrequency &&
601 fNumOctaves == s.fNumOctaves &&
602 fStitchTiles == s.fStitchTiles &&
603 fCoordTransform.getMatrix() == s.fCoordTransform.getMatrix() &&
607 GrNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, int numOctaves,
608 bool stitchTiles, const SkMatrix& matrix, uint8_t alpha)
610 , fBaseFrequency(baseFrequency)
611 , fNumOctaves(numOctaves)
612 , fStitchTiles(stitchTiles)
615 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
616 // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions.
618 m.postTranslate(SK_Scalar1, SK_Scalar1);
619 fCoordTransform.reset(kLocal_GrCoordSet, m);
620 this->addCoordTransform(&fCoordTransform);
621 this->setWillNotUseInputColor();
624 SkPerlinNoiseShader::Type fType;
625 GrCoordTransform fCoordTransform;
626 SkVector fBaseFrequency;
633 typedef GrEffect INHERITED;
636 class GrPerlinNoiseEffect : public GrNoiseEffect {
638 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
639 int numOctaves, bool stitchTiles,
640 const SkPerlinNoiseShader::StitchData& stitchData,
641 GrTexture* permutationsTexture, GrTexture* noiseTexture,
642 const SkMatrix& matrix, uint8_t alpha) {
643 AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves,
644 stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha)));
645 return CreateEffectRef(effect);
648 virtual ~GrPerlinNoiseEffect() { }
650 static const char* Name() { return "PerlinNoise"; }
651 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
652 return GrTBackendEffectFactory<GrPerlinNoiseEffect>::getInstance();
654 const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; }
656 typedef GrGLPerlinNoise GLEffect;
659 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
660 const GrPerlinNoiseEffect& s = CastEffect<GrPerlinNoiseEffect>(sBase);
661 return INHERITED::onIsEqual(sBase) &&
662 fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() &&
663 fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() &&
664 fStitchData == s.fStitchData;
667 GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
668 int numOctaves, bool stitchTiles,
669 const SkPerlinNoiseShader::StitchData& stitchData,
670 GrTexture* permutationsTexture, GrTexture* noiseTexture,
671 const SkMatrix& matrix, uint8_t alpha)
672 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
673 , fPermutationsAccess(permutationsTexture)
674 , fNoiseAccess(noiseTexture)
675 , fStitchData(stitchData) {
676 this->addTextureAccess(&fPermutationsAccess);
677 this->addTextureAccess(&fNoiseAccess);
680 GR_DECLARE_EFFECT_TEST;
682 GrTextureAccess fPermutationsAccess;
683 GrTextureAccess fNoiseAccess;
684 SkPerlinNoiseShader::StitchData fStitchData;
686 typedef GrNoiseEffect INHERITED;
689 class GrSimplexNoiseEffect : public GrNoiseEffect {
690 // Note : This is for reference only. GrPerlinNoiseEffect is used for processing.
692 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
693 int numOctaves, bool stitchTiles, const SkScalar seed,
694 const SkMatrix& matrix, uint8_t alpha) {
695 AutoEffectUnref effect(SkNEW_ARGS(GrSimplexNoiseEffect, (type, baseFrequency, numOctaves,
696 stitchTiles, seed, matrix, alpha)));
697 return CreateEffectRef(effect);
700 virtual ~GrSimplexNoiseEffect() { }
702 static const char* Name() { return "SimplexNoise"; }
703 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
704 return GrTBackendEffectFactory<GrSimplexNoiseEffect>::getInstance();
706 const SkScalar& seed() const { return fSeed; }
708 typedef GrGLSimplexNoise GLEffect;
711 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
712 const GrSimplexNoiseEffect& s = CastEffect<GrSimplexNoiseEffect>(sBase);
713 return INHERITED::onIsEqual(sBase) && fSeed == s.fSeed;
716 GrSimplexNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
717 int numOctaves, bool stitchTiles, const SkScalar seed,
718 const SkMatrix& matrix, uint8_t alpha)
719 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
725 typedef GrNoiseEffect INHERITED;
728 /////////////////////////////////////////////////////////////////////
729 GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect);
731 GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkRandom* random,
733 const GrDrawTargetCaps&,
735 int numOctaves = random->nextRangeU(2, 10);
736 bool stitchTiles = random->nextBool();
737 SkScalar seed = SkIntToScalar(random->nextU());
738 SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
739 SkScalar baseFrequencyX = random->nextRangeScalar(0.01f,
741 SkScalar baseFrequencyY = random->nextRangeScalar(0.01f,
744 SkShader* shader = random->nextBool() ?
745 SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
746 stitchTiles ? &tileSize : NULL) :
747 SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
748 stitchTiles ? &tileSize : NULL);
751 GrEffectRef* effect = shader->asNewEffect(context, paint);
758 /////////////////////////////////////////////////////////////////////
760 void GrGLSimplexNoise::emitCode(GrGLShaderBuilder* builder,
763 const char* outputColor,
764 const char* inputColor,
765 const TransformedCoordsArray& coords,
766 const TextureSamplerArray&) {
767 sk_ignore_unused_variable(inputColor);
769 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
771 fSeedUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
772 kFloat_GrSLType, "seed");
773 const char* seedUni = builder->getUniformCStr(fSeedUni);
774 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
775 kMat33f_GrSLType, "invMatrix");
776 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
777 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
778 kVec2f_GrSLType, "baseFrequency");
779 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
780 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
781 kFloat_GrSLType, "alpha");
782 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
784 // Add vec3 modulo 289 function
785 static const GrGLShaderVar gVec3Args[] = {
786 GrGLShaderVar("x", kVec3f_GrSLType)
789 SkString mod289_3_funcName;
790 builder->fsEmitFunction(kVec3f_GrSLType,
791 "mod289", SK_ARRAY_COUNT(gVec3Args), gVec3Args,
792 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
793 "return x - floor(x * C.xxx) * C.yyy;", &mod289_3_funcName);
795 // Add vec4 modulo 289 function
796 static const GrGLShaderVar gVec4Args[] = {
797 GrGLShaderVar("x", kVec4f_GrSLType)
800 SkString mod289_4_funcName;
801 builder->fsEmitFunction(kVec4f_GrSLType,
802 "mod289", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
803 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
804 "return x - floor(x * C.xxxx) * C.yyyy;", &mod289_4_funcName);
806 // Add vec4 permute function
807 SkString permuteCode;
808 permuteCode.appendf("const vec2 C = vec2(34.0, 1.0);\n"
809 "return %s(((x * C.xxxx) + C.yyyy) * x);", mod289_4_funcName.c_str());
810 SkString permuteFuncName;
811 builder->fsEmitFunction(kVec4f_GrSLType,
812 "permute", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
813 permuteCode.c_str(), &permuteFuncName);
815 // Add vec4 taylorInvSqrt function
816 SkString taylorInvSqrtFuncName;
817 builder->fsEmitFunction(kVec4f_GrSLType,
818 "taylorInvSqrt", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
819 "const vec2 C = vec2(-0.85373472095314, 1.79284291400159);\n"
820 "return x * C.xxxx + C.yyyy;", &taylorInvSqrtFuncName);
822 // Add vec3 noise function
823 static const GrGLShaderVar gNoiseVec3Args[] = {
824 GrGLShaderVar("v", kVec3f_GrSLType)
829 "const vec2 C = vec2(1.0/6.0, 1.0/3.0);\n"
830 "const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n"
833 "vec3 i = floor(v + dot(v, C.yyy));\n"
834 "vec3 x0 = v - i + dot(i, C.xxx);\n"
837 "vec3 g = step(x0.yzx, x0.xyz);\n"
838 "vec3 l = 1.0 - g;\n"
839 "vec3 i1 = min(g.xyz, l.zxy);\n"
840 "vec3 i2 = max(g.xyz, l.zxy);\n"
842 "vec3 x1 = x0 - i1 + C.xxx;\n"
843 "vec3 x2 = x0 - i2 + C.yyy;\n" // 2.0*C.x = 1/3 = C.y
844 "vec3 x3 = x0 - D.yyy;\n" // -1.0+3.0*C.x = -0.5 = -D.y
850 "vec4 p = %s(%s(%s(\n"
851 " i.z + vec4(0.0, i1.z, i2.z, 1.0)) +\n"
852 " i.y + vec4(0.0, i1.y, i2.y, 1.0)) +\n"
853 " i.x + vec4(0.0, i1.x, i2.x, 1.0));\n",
854 mod289_3_funcName.c_str(), permuteFuncName.c_str(), permuteFuncName.c_str(),
855 permuteFuncName.c_str());
858 // Gradients: 7x7 points over a square, mapped onto an octahedron.
859 // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
860 "float n_ = 0.142857142857;\n" // 1.0/7.0
861 "vec3 ns = n_ * D.wyz - D.xzx;\n"
863 "vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\n" // mod(p,7*7)
865 "vec4 x_ = floor(j * ns.z);\n"
866 "vec4 y_ = floor(j - 7.0 * x_);" // mod(j,N)
868 "vec4 x = x_ *ns.x + ns.yyyy;\n"
869 "vec4 y = y_ *ns.x + ns.yyyy;\n"
870 "vec4 h = 1.0 - abs(x) - abs(y);\n"
872 "vec4 b0 = vec4(x.xy, y.xy);\n"
873 "vec4 b1 = vec4(x.zw, y.zw);\n"
877 "vec4 s0 = floor(b0) * 2.0 + 1.0;\n"
878 "vec4 s1 = floor(b1) * 2.0 + 1.0;\n"
879 "vec4 sh = -step(h, vec4(0.0));\n"
881 "vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;\n"
882 "vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;\n"
884 "vec3 p0 = vec3(a0.xy, h.x);\n"
885 "vec3 p1 = vec3(a0.zw, h.y);\n"
886 "vec3 p2 = vec3(a1.xy, h.z);\n"
887 "vec3 p3 = vec3(a1.zw, h.w);\n"
891 // Normalise gradients
892 "vec4 norm = %s(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n"
898 // Mix final noise value
899 "vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n"
901 "return 42.0 * dot(m*m, vec4(dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3)));",
902 taylorInvSqrtFuncName.c_str());
904 SkString noiseFuncName;
905 builder->fsEmitFunction(kFloat_GrSLType,
906 "snoise", SK_ARRAY_COUNT(gNoiseVec3Args), gNoiseVec3Args,
907 noiseCode.c_str(), &noiseFuncName);
909 const char* noiseVecIni = "noiseVecIni";
910 const char* factors = "factors";
911 const char* sum = "sum";
912 const char* xOffsets = "xOffsets";
913 const char* yOffsets = "yOffsets";
914 const char* channel = "channel";
916 // Fill with some prime numbers
917 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(13.0, 53.0, 101.0, 151.0);\n", xOffsets);
918 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(109.0, 167.0, 23.0, 67.0);\n", yOffsets);
920 // There are rounding errors if the floor operation is not performed here
921 builder->fsCodeAppendf(
922 "\t\tvec3 %s = vec3(floor((%s*vec3(%s, 1.0)).xy) * vec2(0.66) * %s, 0.0);\n",
923 noiseVecIni, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
925 // Perturb the texcoords with three components of noise
926 builder->fsCodeAppendf("\t\t%s += 0.1 * vec3(%s(%s + vec3( 0.0, 0.0, %s)),"
927 "%s(%s + vec3( 43.0, 17.0, %s)),"
928 "%s(%s + vec3(-17.0, -43.0, %s)));\n",
929 noiseVecIni, noiseFuncName.c_str(), noiseVecIni, seedUni,
930 noiseFuncName.c_str(), noiseVecIni, seedUni,
931 noiseFuncName.c_str(), noiseVecIni, seedUni);
933 builder->fsCodeAppendf("\t\t%s = vec4(0.0);\n", outputColor);
935 builder->fsCodeAppendf("\t\tvec3 %s = vec3(1.0);\n", factors);
936 builder->fsCodeAppendf("\t\tfloat %s = 0.0;\n", sum);
938 // Loop over all octaves
939 builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {\n", fNumOctaves);
941 // Loop over the 4 channels
942 builder->fsCodeAppendf("\t\t\tfor (int %s = 3; %s >= 0; --%s) {\n", channel, channel, channel);
944 builder->fsCodeAppendf(
945 "\t\t\t\t%s[channel] += %s.x * %s(%s * %s.yyy - vec3(%s[%s], %s[%s], %s * %s.z));\n",
946 outputColor, factors, noiseFuncName.c_str(), noiseVecIni, factors, xOffsets, channel,
947 yOffsets, channel, seedUni, factors);
949 builder->fsCodeAppend("\t\t\t}\n"); // end of the for loop on channels
951 builder->fsCodeAppendf("\t\t\t%s += %s.x;\n", sum, factors);
952 builder->fsCodeAppendf("\t\t\t%s *= vec3(0.5, 2.0, 0.75);\n", factors);
954 builder->fsCodeAppend("\t\t}\n"); // end of the for loop on octaves
956 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
957 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
958 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
959 builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5 / %s) + vec4(0.5);\n",
960 outputColor, outputColor, sum);
962 builder->fsCodeAppendf("\t\t%s = abs(%s / vec4(%s));\n",
963 outputColor, outputColor, sum);
966 builder->fsCodeAppendf("\t\t%s.a *= %s;\n", outputColor, alphaUni);
969 builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);\n", outputColor, outputColor);
971 // Pre-multiply the result
972 builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
973 outputColor, outputColor, outputColor, outputColor);
976 void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder,
979 const char* outputColor,
980 const char* inputColor,
981 const TransformedCoordsArray& coords,
982 const TextureSamplerArray& samplers) {
983 sk_ignore_unused_variable(inputColor);
985 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
987 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
988 kMat33f_GrSLType, "invMatrix");
989 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
990 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
991 kVec2f_GrSLType, "baseFrequency");
992 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
993 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
994 kFloat_GrSLType, "alpha");
995 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
997 const char* stitchDataUni = NULL;
999 fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
1000 kVec2f_GrSLType, "stitchData");
1001 stitchDataUni = builder->getUniformCStr(fStitchDataUni);
1004 // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
1005 const char* chanCoordR = "0.125";
1006 const char* chanCoordG = "0.375";
1007 const char* chanCoordB = "0.625";
1008 const char* chanCoordA = "0.875";
1009 const char* chanCoord = "chanCoord";
1010 const char* stitchData = "stitchData";
1011 const char* ratio = "ratio";
1012 const char* noiseXY = "noiseXY";
1013 const char* noiseVec = "noiseVec";
1014 const char* noiseSmooth = "noiseSmooth";
1015 const char* fractVal = "fractVal";
1016 const char* uv = "uv";
1017 const char* ab = "ab";
1018 const char* latticeIdx = "latticeIdx";
1019 const char* lattice = "lattice";
1020 const char* inc8bit = "0.00390625"; // 1.0 / 256.0
1021 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
1022 // [-1,1] vector and perform a dot product between that vector and the provided vector.
1023 const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
1025 // Add noise function
1026 static const GrGLShaderVar gPerlinNoiseArgs[] = {
1027 GrGLShaderVar(chanCoord, kFloat_GrSLType),
1028 GrGLShaderVar(noiseVec, kVec2f_GrSLType)
1031 static const GrGLShaderVar gPerlinNoiseStitchArgs[] = {
1032 GrGLShaderVar(chanCoord, kFloat_GrSLType),
1033 GrGLShaderVar(noiseVec, kVec2f_GrSLType),
1034 GrGLShaderVar(stitchData, kVec2f_GrSLType)
1039 noiseCode.appendf("\tvec4 %s = vec4(floor(%s), fract(%s));", noiseXY, noiseVec, noiseVec);
1041 // smooth curve : t * t * (3 - 2 * t)
1042 noiseCode.appendf("\n\tvec2 %s = %s.zw * %s.zw * (vec2(3.0) - vec2(2.0) * %s.zw);",
1043 noiseSmooth, noiseXY, noiseXY, noiseXY);
1045 // Adjust frequencies if we're stitching tiles
1047 noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
1048 noiseXY, stitchData, noiseXY, stitchData);
1049 noiseCode.appendf("\n\tif(%s.x >= (%s.x - 1.0)) { %s.x -= (%s.x - 1.0); }",
1050 noiseXY, stitchData, noiseXY, stitchData);
1051 noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }",
1052 noiseXY, stitchData, noiseXY, stitchData);
1053 noiseCode.appendf("\n\tif(%s.y >= (%s.y - 1.0)) { %s.y -= (%s.y - 1.0); }",
1054 noiseXY, stitchData, noiseXY, stitchData);
1057 // Get texture coordinates and normalize
1058 noiseCode.appendf("\n\t%s.xy = fract(floor(mod(%s.xy, 256.0)) / vec2(256.0));\n",
1061 // Get permutation for x
1063 SkString xCoords("");
1064 xCoords.appendf("vec2(%s.x, 0.5)", noiseXY);
1066 noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
1067 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1068 noiseCode.append(".r;");
1071 // Get permutation for x + 1
1073 SkString xCoords("");
1074 xCoords.appendf("vec2(fract(%s.x + %s), 0.5)", noiseXY, inc8bit);
1076 noiseCode.appendf("\n\t%s.y = ", latticeIdx);
1077 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1078 noiseCode.append(".r;");
1081 #if defined(SK_BUILD_FOR_ANDROID)
1082 // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
1083 // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
1084 // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
1085 // (or 0.484368 here). The following rounding operation prevents these precision issues from
1086 // affecting the result of the noise by making sure that we only have multiples of 1/255.
1087 // (Note that 1/255 is about 0.003921569, which is the value used here).
1088 noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);",
1089 latticeIdx, latticeIdx);
1092 // Get (x,y) coordinates with the permutated x
1093 noiseCode.appendf("\n\t%s = fract(%s + %s.yy);", latticeIdx, latticeIdx, noiseXY);
1095 noiseCode.appendf("\n\tvec2 %s = %s.zw;", fractVal, noiseXY);
1097 noiseCode.appendf("\n\n\tvec2 %s;", uv);
1098 // Compute u, at offset (0,0)
1100 SkString latticeCoords("");
1101 latticeCoords.appendf("vec2(%s.x, %s)", latticeIdx, chanCoord);
1102 noiseCode.appendf("\n\tvec4 %s = ", lattice);
1103 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1105 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1106 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
1109 noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
1110 // Compute v, at offset (-1,0)
1112 SkString latticeCoords("");
1113 latticeCoords.appendf("vec2(%s.y, %s)", latticeIdx, chanCoord);
1114 noiseCode.append("\n\tlattice = ");
1115 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1117 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1118 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
1121 // Compute 'a' as a linear interpolation of 'u' and 'v'
1122 noiseCode.appendf("\n\tvec2 %s;", ab);
1123 noiseCode.appendf("\n\t%s.x = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
1125 noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
1126 // Compute v, at offset (-1,-1)
1128 SkString latticeCoords("");
1129 latticeCoords.appendf("vec2(fract(%s.y + %s), %s)", latticeIdx, inc8bit, chanCoord);
1130 noiseCode.append("\n\tlattice = ");
1131 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1133 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1134 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
1137 noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
1138 // Compute u, at offset (0,-1)
1140 SkString latticeCoords("");
1141 latticeCoords.appendf("vec2(fract(%s.x + %s), %s)", latticeIdx, inc8bit, chanCoord);
1142 noiseCode.append("\n\tlattice = ");
1143 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1145 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1146 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
1149 // Compute 'b' as a linear interpolation of 'u' and 'v'
1150 noiseCode.appendf("\n\t%s.y = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
1151 // Compute the noise as a linear interpolation of 'a' and 'b'
1152 noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
1154 SkString noiseFuncName;
1156 builder->fsEmitFunction(kFloat_GrSLType,
1157 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
1158 gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
1160 builder->fsEmitFunction(kFloat_GrSLType,
1161 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
1162 gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
1165 // There are rounding errors if the floor operation is not performed here
1166 builder->fsCodeAppendf("\n\t\tvec2 %s = floor((%s * vec3(%s, 1.0)).xy) * %s;",
1167 noiseVec, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
1169 // Clear the color accumulator
1170 builder->fsCodeAppendf("\n\t\t%s = vec4(0.0);", outputColor);
1173 // Set up TurbulenceInitial stitch values.
1174 builder->fsCodeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni);
1177 builder->fsCodeAppendf("\n\t\tfloat %s = 1.0;", ratio);
1179 // Loop over all octaves
1180 builder->fsCodeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
1182 builder->fsCodeAppendf("\n\t\t\t%s += ", outputColor);
1183 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1184 builder->fsCodeAppend("abs(");
1187 builder->fsCodeAppendf(
1188 "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
1189 "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
1190 noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
1191 noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
1192 noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
1193 noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
1195 builder->fsCodeAppendf(
1196 "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
1197 "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
1198 noiseFuncName.c_str(), chanCoordR, noiseVec,
1199 noiseFuncName.c_str(), chanCoordG, noiseVec,
1200 noiseFuncName.c_str(), chanCoordB, noiseVec,
1201 noiseFuncName.c_str(), chanCoordA, noiseVec);
1203 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1204 builder->fsCodeAppendf(")"); // end of "abs("
1206 builder->fsCodeAppendf(" * %s;", ratio);
1208 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
1209 builder->fsCodeAppendf("\n\t\t\t%s *= 0.5;", ratio);
1212 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData);
1214 builder->fsCodeAppend("\n\t\t}"); // end of the for loop on octaves
1216 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
1217 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
1218 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
1219 builder->fsCodeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
1222 builder->fsCodeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni);
1225 builder->fsCodeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
1227 // Pre-multiply the result
1228 builder->fsCodeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
1229 outputColor, outputColor, outputColor, outputColor);
1232 GrGLNoise::GrGLNoise(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect)
1233 : INHERITED (factory)
1234 , fType(drawEffect.castEffect<GrPerlinNoiseEffect>().type())
1235 , fStitchTiles(drawEffect.castEffect<GrPerlinNoiseEffect>().stitchTiles())
1236 , fNumOctaves(drawEffect.castEffect<GrPerlinNoiseEffect>().numOctaves()) {
1239 GrGLEffect::EffectKey GrGLNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) {
1240 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1242 EffectKey key = turbulence.numOctaves();
1244 key = key << 3; // Make room for next 3 bits
1246 switch (turbulence.type()) {
1247 case SkPerlinNoiseShader::kFractalNoise_Type:
1250 case SkPerlinNoiseShader::kTurbulence_Type:
1258 if (turbulence.stitchTiles()) {
1259 key |= 0x4; // Flip the 3rd bit if tile stitching is on
1265 void GrGLNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1266 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1268 const SkVector& baseFrequency = turbulence.baseFrequency();
1269 uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
1270 uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
1272 SkMatrix m = turbulence.matrix();
1273 m.postTranslate(-SK_Scalar1, -SK_Scalar1);
1275 if (!m.invert(&invM)) {
1278 invM.postConcat(invM); // Square the matrix
1280 uman.setSkMatrix(fInvMatrixUni, invM);
1283 void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1284 INHERITED::setData(uman, drawEffect);
1286 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1287 if (turbulence.stitchTiles()) {
1288 const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
1289 uman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
1290 SkIntToScalar(stitchData.fHeight));
1294 void GrGLSimplexNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1295 INHERITED::setData(uman, drawEffect);
1297 const GrSimplexNoiseEffect& turbulence = drawEffect.castEffect<GrSimplexNoiseEffect>();
1298 uman.set1f(fSeedUni, turbulence.seed());
1301 /////////////////////////////////////////////////////////////////////
1303 GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
1304 SkASSERT(NULL != context);
1306 if (0 == fNumOctaves) {
1307 SkColor clearColor = 0;
1308 if (kFractalNoise_Type == fType) {
1309 clearColor = SkColorSetARGB(paint.getAlpha() / 2, 127, 127, 127);
1311 SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(
1312 clearColor, SkXfermode::kSrc_Mode));
1313 return cf->asNewEffect(context);
1316 // Either we don't stitch tiles, either we have a valid tile size
1317 SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
1319 #ifdef SK_USE_SIMPLEX_NOISE
1320 // Simplex noise is currently disabled but can be enabled by defining SK_USE_SIMPLEX_NOISE
1321 sk_ignore_unused_variable(context);
1322 GrEffectRef* effect =
1323 GrSimplexNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
1324 fNumOctaves, fStitchTiles, fSeed,
1325 this->getLocalMatrix(), paint.getAlpha());
1327 GrTexture* permutationsTexture = GrLockAndRefCachedBitmapTexture(
1328 context, *fPaintingData->getPermutationsBitmap(), NULL);
1329 GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture(
1330 context, *fPaintingData->getNoiseBitmap(), NULL);
1332 GrEffectRef* effect = (NULL != permutationsTexture) && (NULL != noiseTexture) ?
1333 GrPerlinNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
1334 fNumOctaves, fStitchTiles,
1335 fPaintingData->fStitchDataInit,
1336 permutationsTexture, noiseTexture,
1337 this->getLocalMatrix(), paint.getAlpha()) :
1340 // Unlock immediately, this is not great, but we don't have a way of
1341 // knowing when else to unlock it currently. TODO: Remove this when
1342 // unref becomes the unlock replacement for all types of textures.
1343 if (NULL != permutationsTexture) {
1344 GrUnlockAndUnrefCachedBitmapTexture(permutationsTexture);
1346 if (NULL != noiseTexture) {
1347 GrUnlockAndUnrefCachedBitmapTexture(noiseTexture);
1356 GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext*, const SkPaint&) const {
1357 SkDEBUGFAIL("Should not call in GPU-less build");
1364 void SkPerlinNoiseShader::toString(SkString* str) const {
1365 str->append("SkPerlinNoiseShader: (");
1367 str->append("type: ");
1369 case kFractalNoise_Type:
1370 str->append("\"fractal noise\"");
1372 case kTurbulence_Type:
1373 str->append("\"turbulence\"");
1376 str->append("\"unknown\"");
1379 str->append(" base frequency: (");
1380 str->appendScalar(fBaseFrequencyX);
1382 str->appendScalar(fBaseFrequencyY);
1383 str->append(") number of octaves: ");
1384 str->appendS32(fNumOctaves);
1385 str->append(" seed: ");
1386 str->appendScalar(fSeed);
1387 str->append(" stitch tiles: ");
1388 str->append(fStitchTiles ? "true " : "false ");
1390 this->INHERITED::toString(str);