blob: 9d9290d5582854e060847784b22ae400d8cf4839 [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
167 static const SkScalar halfMax16bits = SkFloatToScalar(32767.5f);
168
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(
180 fGradient[channel][i].fX + SK_Scalar1, halfMax16bits));
181 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
182 fGradient[channel][i].fY + SK_Scalar1, halfMax16bits));
183 }
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
497#if SK_SUPPORT_GPU
498
499#include "GrTBackendEffectFactory.h"
500
501class GrGLPerlinNoise : public GrGLEffect {
502public:
503
504 GrGLPerlinNoise(const GrBackendEffectFactory& factory,
505 const GrDrawEffect& drawEffect);
506 virtual ~GrGLPerlinNoise() { }
507
508 virtual void emitCode(GrGLShaderBuilder*,
509 const GrDrawEffect&,
510 EffectKey,
511 const char* outputColor,
512 const char* inputColor,
513 const TextureSamplerArray&) SK_OVERRIDE;
514
515 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
516
517 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&);
518
519private:
520 SkPerlinNoiseShader::Type fType;
521 bool fStitchTiles;
522 int fNumOctaves;
523 GrGLUniformManager::UniformHandle fBaseFrequencyUni;
524 GrGLUniformManager::UniformHandle fStitchDataUni;
525 GrGLUniformManager::UniformHandle fAlphaUni;
526 GrGLUniformManager::UniformHandle fInvMatrixUni;
527 GrGLEffectMatrix fEffectMatrix;
528
529 typedef GrGLEffect INHERITED;
530};
531
532/////////////////////////////////////////////////////////////////////
533
534class GrPerlinNoiseEffect : public GrEffect {
535public:
536 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
537 int numOctaves, bool stitchTiles,
538 const SkPerlinNoiseShader::StitchData& stitchData,
539 GrTexture* permutationsTexture, GrTexture* noiseTexture,
540 const SkMatrix& matrix, uint8_t alpha) {
541 AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves,
542 stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha)));
543 return CreateEffectRef(effect);
544 }
545
546 virtual ~GrPerlinNoiseEffect() { }
547
548 static const char* Name() { return "PerlinNoise"; }
549 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
550 return GrTBackendEffectFactory<GrPerlinNoiseEffect>::getInstance();
551 }
552 SkPerlinNoiseShader::Type type() const { return fType; }
553 bool stitchTiles() const { return fStitchTiles; }
554 const SkVector& baseFrequency() const { return fBaseFrequency; }
555 int numOctaves() const { return fNumOctaves & 0xFF; /*[0,255] octaves allowed*/ }
556 const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; }
557 const SkMatrix& matrix() const { return fMatrix; }
558 uint8_t alpha() const { return fAlpha; }
559 GrGLEffectMatrix::CoordsType coordsType() const { return GrEffect::kLocal_CoordsType; }
560
561 typedef GrGLPerlinNoise GLEffect;
562
563 void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE {
564 *validFlags = 0; // This is noise. Nothing is constant.
565 }
566
567private:
568 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
569 const GrPerlinNoiseEffect& s = CastEffect<GrPerlinNoiseEffect>(sBase);
570 return fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() &&
571 fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() &&
572 fType == s.fType &&
573 fBaseFrequency == s.fBaseFrequency &&
574 fStitchTiles == s.fStitchTiles &&
575 fStitchData == s.fStitchData &&
576 fMatrix == s.fMatrix &&
577 fAlpha == s.fAlpha;
578 }
579
580 GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
581 int numOctaves, bool stitchTiles,
582 const SkPerlinNoiseShader::StitchData& stitchData,
583 GrTexture* permutationsTexture, GrTexture* noiseTexture,
584 const SkMatrix& matrix, uint8_t alpha)
585 : fPermutationsAccess(permutationsTexture)
586 , fNoiseAccess(noiseTexture)
587 , fType(type)
588 , fBaseFrequency(baseFrequency)
589 , fNumOctaves(numOctaves)
590 , fStitchTiles(stitchTiles)
591 , fStitchData(stitchData)
592 , fMatrix(matrix)
593 , fAlpha(alpha)
594 {
595 this->addTextureAccess(&fPermutationsAccess);
596 this->addTextureAccess(&fNoiseAccess);
597 }
598
sugoi@google.comb4bdb652013-04-05 14:38:08 +0000599// GR_DECLARE_EFFECT_TEST;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000600
601 GrTextureAccess fPermutationsAccess;
602 GrTextureAccess fNoiseAccess;
603 SkPerlinNoiseShader::Type fType;
604 SkVector fBaseFrequency;
605 int fNumOctaves;
606 bool fStitchTiles;
607 SkPerlinNoiseShader::StitchData fStitchData;
608 SkMatrix fMatrix;
609 uint8_t fAlpha;
610
611 typedef GrEffect INHERITED;
612};
613
614/////////////////////////////////////////////////////////////////////
sugoi@google.comb4bdb652013-04-05 14:38:08 +0000615#if 0
sugoi@google.come3b4c502013-04-05 13:47:09 +0000616GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect);
617
618GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkMWCRandom* random,
619 GrContext* context,
620 const GrDrawTargetCaps&,
621 GrTexture**) {
622 int numOctaves = random->nextRangeU(2, 10);
623 bool stitchTiles = random->nextBool();
624 SkScalar seed = SkIntToScalar(random->nextU());
625 SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
626 SkScalar baseFrequencyX = random->nextRangeScalar(SkFloatToScalar(0.01f),
627 SkFloatToScalar(0.99f));
628 SkScalar baseFrequencyY = random->nextRangeScalar(SkFloatToScalar(0.01f),
629 SkFloatToScalar(0.99f));
630
631 SkShader* shader = random->nextBool() ?
632 SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
633 stitchTiles ? &tileSize : NULL) :
634 SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
635 stitchTiles ? &tileSize : NULL);
636
637 SkPaint paint;
638 GrEffectRef* effect = shader->asNewEffect(context, paint);
639
640 SkDELETE(shader);
641
642 return effect;
643}
sugoi@google.comb4bdb652013-04-05 14:38:08 +0000644#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +0000645/////////////////////////////////////////////////////////////////////
646
647void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder,
648 const GrDrawEffect&,
649 EffectKey key,
650 const char* outputColor,
651 const char* inputColor,
652 const TextureSamplerArray& samplers) {
653 sk_ignore_unused_variable(inputColor);
654
655 const char* vCoords;
656 fEffectMatrix.emitCodeMakeFSCoords2D(builder, key, &vCoords);
657
658 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
659 kMat33f_GrSLType, "invMatrix");
660 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
661 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
662 kVec2f_GrSLType, "baseFrequency");
663 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
664 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
665 kFloat_GrSLType, "alpha");
666 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
667
668 const char* stitchDataUni = NULL;
669 if (fStitchTiles) {
670 fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
671 kVec4f_GrSLType, "stitchData");
672 stitchDataUni = builder->getUniformCStr(fStitchDataUni);
673 }
674
675 const char* chanCoords = "chanCoords";
676 const char* stitchData = "stitchData";
677 const char* ratio = "ratio";
678 const char* noise = "noise";
679 const char* noiseXY = "noiseXY";
680 const char* noiseVec = "noiseVec";
681 const char* noiseVecIni = "noiseVecIni";
682 const char* noiseSmooth = "noiseSmooth";
683 const char* fractVal = "fractVal";
684 const char* uv = "uv";
685 const char* ab = "ab";
686 const char* latticeIdx = "latticeIdx";
687 const char* lattice = "lattice";
688 const char* perlinNoise = "4096.0";
689 const char* inc8bit = "0.00390625"; // 1.0 / 256.0
690 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
691 // [-1,1] vector and perform a dot product between that vector and the provided vector.
692 const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
693
694 // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
695 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(0.125, 0.375, 0.625, 0.875);", chanCoords);
696
697 // There are rounding errors if the floor operation is not performed here
698 builder->fsCodeAppendf("\t\tvec2 %s = floor((%s*vec3(%s, 1.0)).xy) * %s;",
699 noiseVecIni, invMatrixUni, vCoords, baseFrequencyUni);
700
701 // Loop over the 4 channels
702 builder->fsCodeAppend("\t\tfor (int channel = 3; channel >= 0; --channel) {");
703
704 if (fStitchTiles) {
705 // Set up TurbulenceInitial stitch values.
706 builder->fsCodeAppendf("\t\tvec4 %s = %s;", stitchData, stitchDataUni);
707 }
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000708
sugoi@google.come3b4c502013-04-05 13:47:09 +0000709 builder->fsCodeAppendf("\t\t%s[channel] = 0.0;", outputColor);
710
711 builder->fsCodeAppendf("\t\tfloat %s = 1.0;", ratio);
712 builder->fsCodeAppendf("\t\tvec2 %s = %s;", noiseVec, noiseVecIni);
713
714 // Loop over all octaves
715 builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
716
717 builder->fsCodeAppendf("\t\tvec4 %s = vec4(floor(%s) + vec2(%s), fract(%s));",
718 noiseXY, noiseVec, perlinNoise, noiseVec);
719
720 // smooth curve : t * t * (3 - 2 * t)
721 builder->fsCodeAppendf("\t\tvec2 %s = %s.zw * %s.zw * (vec2(3.0) - vec2(2.0) * %s.zw);",
722 noiseSmooth, noiseXY, noiseXY, noiseXY);
723
724 // Adjust frequencies if we're stitching tiles
725 if (fStitchTiles) {
726 builder->fsCodeAppendf("\t\tif(%s.x >= %s.y) { %s.x -= %s.x; }",
727 noiseXY, stitchData, noiseXY, stitchData);
728 builder->fsCodeAppendf("\t\tif(%s.x >= (%s.y - 1.0)) { %s.x -= (%s.x - 1.0); }",
729 noiseXY, stitchData, noiseXY, stitchData);
730 builder->fsCodeAppendf("\t\tif(%s.y >= %s.w) { %s.y -= %s.z; }",
731 noiseXY, stitchData, noiseXY, stitchData);
732 builder->fsCodeAppendf("\t\tif(%s.y >= (%s.w - 1.0)) { %s.y -= (%s.z - 1.0); }",
733 noiseXY, stitchData, noiseXY, stitchData);
734 }
735
736 // Get texture coordinates and normalize
737 builder->fsCodeAppendf("\t\t%s.xy = fract(floor(mod(%s.xy, 256.0)) / vec2(256.0));",
738 noiseXY, noiseXY);
739
740 // Get permutation for x
741 {
742 SkString xCoords("");
743 xCoords.appendf("vec2(%s.x, 0.5)", noiseXY);
744
745 builder->fsCodeAppendf("\t\tvec2 %s;\t\t%s.x = ", latticeIdx, latticeIdx);
746 builder->appendTextureLookup(GrGLShaderBuilder::kFragment_ShaderType,
747 samplers[0], xCoords.c_str(), kVec2f_GrSLType);
748 builder->fsCodeAppend(".r;\n");
749 }
750
751 // Get permutation for x + 1
752 {
753 SkString xCoords("");
754 xCoords.appendf("vec2(fract(%s.x + %s), 0.5)", noiseXY, inc8bit);
755
756 builder->fsCodeAppendf("\t\t%s.y = ", latticeIdx);
757 builder->appendTextureLookup(GrGLShaderBuilder::kFragment_ShaderType,
758 samplers[0], xCoords.c_str(), kVec2f_GrSLType);
759 builder->fsCodeAppend(".r;\n");
760 }
761
762 // Get (x,y) coordinates with the permutated x
763 builder->fsCodeAppendf("\t\t%s = fract(%s + %s.yy);", latticeIdx, latticeIdx, noiseXY);
764
765 builder->fsCodeAppendf("\t\tvec2 %s = %s.zw;", fractVal, noiseXY);
766
767 builder->fsCodeAppendf("\t\tvec2 %s;", uv);
768 // Compute u, at offset (0,0)
769 {
770 SkString latticeCoords("");
771 latticeCoords.appendf("vec2(%s.x, %s[channel])", latticeIdx, chanCoords);
772 builder->fsCodeAppendf("vec4 %s = ", lattice);
773 builder->appendTextureLookup(GrGLShaderBuilder::kFragment_ShaderType,
774 samplers[1], latticeCoords.c_str(), kVec2f_GrSLType);
775 builder->fsCodeAppendf(".bgra;\n\t\t%s.x = ", uv);
776 builder->fsCodeAppendf(dotLattice, lattice, lattice, inc8bit, fractVal);
777 }
778
779 builder->fsCodeAppendf("\t\t%s.x -= 1.0;", fractVal);
780 // Compute v, at offset (-1,0)
781 {
782 SkString latticeCoords("");
783 latticeCoords.appendf("vec2(%s.y, %s[channel])", latticeIdx, chanCoords);
784 builder->fsCodeAppend("lattice = ");
785 builder->appendTextureLookup(GrGLShaderBuilder::kFragment_ShaderType,
786 samplers[1], latticeCoords.c_str(), kVec2f_GrSLType);
787 builder->fsCodeAppendf(".bgra;\n\t\t%s.y = ", uv);
788 builder->fsCodeAppendf(dotLattice, lattice, lattice, inc8bit, fractVal);
789 }
790
791 // Compute 'a' as a linear interpolation of 'u' and 'v'
792 builder->fsCodeAppendf("\t\tvec2 %s;", ab);
793 builder->fsCodeAppendf("\t\t%s.x = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
794
795 builder->fsCodeAppendf("\t\t%s.y -= 1.0;", fractVal);
796 // Compute v, at offset (-1,-1)
797 {
798 SkString latticeCoords("");
799 latticeCoords.appendf("vec2(fract(%s.y + %s), %s[channel])",
800 latticeIdx, inc8bit, chanCoords);
801 builder->fsCodeAppend("lattice = ");
802 builder->appendTextureLookup(GrGLShaderBuilder::kFragment_ShaderType,
803 samplers[1], latticeCoords.c_str(), kVec2f_GrSLType);
804 builder->fsCodeAppendf(".bgra;\n\t\t%s.y = ", uv);
805 builder->fsCodeAppendf(dotLattice, lattice, lattice, inc8bit, fractVal);
806 }
807
808 builder->fsCodeAppendf("\t\t%s.x += 1.0;", fractVal);
809 // Compute u, at offset (0,-1)
810 {
811 SkString latticeCoords("");
812 latticeCoords.appendf("vec2(fract(%s.x + %s), %s[channel])",
813 latticeIdx, inc8bit, chanCoords);
814 builder->fsCodeAppend("lattice = ");
815 builder->appendTextureLookup(GrGLShaderBuilder::kFragment_ShaderType,
816 samplers[1], latticeCoords.c_str(), kVec2f_GrSLType);
817 builder->fsCodeAppendf(".bgra;\n\t\t%s.x = ", uv);
818 builder->fsCodeAppendf(dotLattice, lattice, lattice, inc8bit, fractVal);
819 }
820
821 // Compute 'b' as a linear interpolation of 'u' and 'v'
822 builder->fsCodeAppendf("\t\t%s.y = mix(%s.x, %s.y, %s.x);", ab, uv, uv, noiseSmooth);
823 // Compute the noise as a linear interpolation of 'a' and 'b'
824 builder->fsCodeAppendf("\t\tfloat %s = mix(%s.x, %s.y, %s.y);", noise, ab, ab, noiseSmooth);
825
826 builder->fsCodeAppendf("\t\t%s[channel] += ", outputColor);
827 builder->fsCodeAppendf((fType == SkPerlinNoiseShader::kFractalNoise_Type) ?
828 "%s / %s;" : "abs(%s) / %s;", noise, ratio);
829
830 builder->fsCodeAppendf("\t\t%s *= vec2(2.0);", noiseVec);
831 builder->fsCodeAppendf("\t\t%s *= 2.0;", ratio);
832
833 if (fStitchTiles) {
834 builder->fsCodeAppendf("\t\t%s.xz *= vec2(2.0);", stitchData);
835 builder->fsCodeAppendf("\t\t%s.yw = %s.xz + vec2(%s);", stitchData, stitchData, perlinNoise);
836 }
837 builder->fsCodeAppend("\t\t}"); // end of the for loop on octaves
838
839 builder->fsCodeAppend("\t\t}"); // end of the for loop on channels
840
841 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
842 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
843 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
844 builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
845 }
846
847 builder->fsCodeAppendf("\t\t%s.a *= %s;", outputColor, alphaUni);
848
849 // Clamp values
850 builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
851
852 // Pre-multiply the result
853 builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
854 outputColor, outputColor, outputColor, outputColor);
855}
856
857GrGLPerlinNoise::GrGLPerlinNoise(const GrBackendEffectFactory& factory,
858 const GrDrawEffect& drawEffect)
859 : INHERITED (factory)
860 , fType(drawEffect.castEffect<GrPerlinNoiseEffect>().type())
861 , fStitchTiles(drawEffect.castEffect<GrPerlinNoiseEffect>().stitchTiles())
862 , fNumOctaves(drawEffect.castEffect<GrPerlinNoiseEffect>().numOctaves())
863 , fEffectMatrix(drawEffect.castEffect<GrPerlinNoiseEffect>().coordsType()) {
864}
865
866GrGLEffect::EffectKey GrGLPerlinNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) {
867 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
868
869 EffectKey key = turbulence.numOctaves();
870
871 key = key << 3; // Make room for next 3 bits
872
873 switch (turbulence.type()) {
874 case SkPerlinNoiseShader::kFractalNoise_Type:
875 key |= 0x1;
876 break;
877 case SkPerlinNoiseShader::kTurbulence_Type:
878 key |= 0x2;
879 break;
880 default:
881 // leave key at 0
882 break;
883 }
884
885 if (turbulence.stitchTiles()) {
886 key |= 0x4; // Flip the 3rd bit if tile stitching is on
887 }
888
889 key = key << GrGLEffectMatrix::kKeyBits;
890
891 SkMatrix m = turbulence.matrix();
892 m.postTranslate(SK_Scalar1, SK_Scalar1);
893 return key | GrGLEffectMatrix::GenKey(m, drawEffect,
894 drawEffect.castEffect<GrPerlinNoiseEffect>().coordsType(), NULL);
895}
896
897void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
898 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
899
900 const SkVector& baseFrequency = turbulence.baseFrequency();
901 uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
902 if (turbulence.stitchTiles()) {
903 const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
904 uman.set4f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
905 SkIntToScalar(stitchData.fWrapX),
906 SkIntToScalar(stitchData.fHeight),
907 SkIntToScalar(stitchData.fWrapY));
908 }
909
910 uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
911
912 SkMatrix m = turbulence.matrix();
913 SkMatrix invM;
914 if (!m.invert(&invM)) {
915 invM.reset();
916 } else {
917 invM.postConcat(invM); // Square the matrix
918 }
919 uman.setSkMatrix(fInvMatrixUni, invM);
920
921 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
922 // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions.
923 m.postTranslate(SK_Scalar1, SK_Scalar1);
924 fEffectMatrix.setData(uman, m, drawEffect, NULL);
925}
926
927/////////////////////////////////////////////////////////////////////
928
929GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
930#if 0
931 SkASSERT(NULL != context);
932
933 // Either we don't stitch tiles, either we have a valid tile size
934 SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
935
936 GrTexture* permutationsTexture = GrLockAndRefCachedBitmapTexture(
937 context, *fPaintingData->getPermutationsBitmap(), NULL);
938 GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture(
939 context, *fPaintingData->getNoiseBitmap(), NULL);
940
941 GrEffectRef* effect = (NULL != permutationsTexture) && (NULL != noiseTexture) ?
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000942 GrPerlinNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000943 fNumOctaves, fStitchTiles,
944 fPaintingData->fStitchDataInit,
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000945 permutationsTexture, noiseTexture,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000946 this->getLocalMatrix(), paint.getAlpha()) :
947 NULL;
948
949 // Unlock immediately, this is not great, but we don't have a way of
950 // knowing when else to unlock it currently. TODO: Remove this when
951 // unref becomes the unlock replacement for all types of textures.
952 if (NULL != permutationsTexture) {
953 GrUnlockAndUnrefCachedBitmapTexture(permutationsTexture);
954 }
955 if (NULL != noiseTexture) {
956 GrUnlockAndUnrefCachedBitmapTexture(noiseTexture);
957 }
958
959 return effect;
960#else
961 sk_ignore_unused_variable(context);
962 sk_ignore_unused_variable(paint);
963 return NULL;
964#endif
965}
966
967#else
968
969GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext*, const SkPaint&) const {
970 SkDEBUGFAIL("Should not call in GPU-less build");
971 return NULL;
972}
973
974#endif
975
976#ifdef SK_DEVELOPER
977void SkPerlinNoiseShader::toString(SkString* str) const {
978 str->append("SkPerlinNoiseShader: (");
979
980 str->append("type: ");
981 switch (fType) {
982 case kFractalNoise_Type:
983 str->append("\"fractal noise\"");
984 break;
985 case kTurbulence_Type:
986 str->append("\"turbulence\"");
987 break;
988 default:
989 str->append("\"unknown\"");
990 break;
991 }
992 str->append(" base frequency: (");
993 str->appendScalar(fBaseFrequencyX);
994 str->append(", ");
995 str->appendScalar(fBaseFrequencyY);
996 str->append(") number of octaves: ");
997 str->appendS32(fNumOctaves);
998 str->append(" seed: ");
999 str->appendScalar(fSeed);
1000 str->append(" stitch tiles: ");
1001 str->append(fStitchTiles ? "true " : "false ");
1002
1003 this->INHERITED::toString(str);
1004
1005 str->append(")");
1006}
1007#endif