blob: 77ce9cb3482346a5ebc719afdad8954146ccbfc1 [file] [log] [blame]
sugoi@google.come3b4c502013-04-05 13:47:09 +00001/*
2 * Copyright 2013 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkDither.h"
9#include "SkPerlinNoiseShader.h"
commit-bot@chromium.orgc2a0ea62013-11-06 10:08:38 +000010#include "SkColorFilter.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000011#include "SkFlattenableBuffers.h"
12#include "SkShader.h"
13#include "SkUnPreMultiply.h"
14#include "SkString.h"
15
16#if SK_SUPPORT_GPU
17#include "GrContext.h"
bsalomon@google.com77af6802013-10-02 13:04:56 +000018#include "GrCoordTransform.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000019#include "gl/GrGLEffect.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000020#include "GrTBackendEffectFactory.h"
21#include "SkGr.h"
22#endif
23
24static const int kBlockSize = 256;
25static const int kBlockMask = kBlockSize - 1;
26static const int kPerlinNoise = 4096;
27static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
28
29namespace {
30
31// noiseValue is the color component's value (or color)
32// limitValue is the maximum perlin noise array index value allowed
33// newValue is the current noise dimension (either width or height)
34inline int checkNoise(int noiseValue, int limitValue, int newValue) {
35 // If the noise value would bring us out of bounds of the current noise array while we are
36 // stiching noise tiles together, wrap the noise around the current dimension of the noise to
37 // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
38 if (noiseValue >= limitValue) {
39 noiseValue -= newValue;
40 }
41 if (noiseValue >= limitValue - 1) {
42 noiseValue -= newValue - 1;
43 }
44 return noiseValue;
45}
46
47inline SkScalar smoothCurve(SkScalar t) {
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +000048 static const SkScalar SK_Scalar3 = 3.0f;
sugoi@google.come3b4c502013-04-05 13:47:09 +000049
50 // returns t * t * (3 - 2 * t)
51 return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
52}
53
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +000054bool perlin_noise_type_is_valid(SkPerlinNoiseShader::Type type) {
55 return (SkPerlinNoiseShader::kFractalNoise_Type == type) ||
56 (SkPerlinNoiseShader::kTurbulence_Type == type);
57}
58
sugoi@google.come3b4c502013-04-05 13:47:09 +000059} // end namespace
60
61struct SkPerlinNoiseShader::StitchData {
62 StitchData()
63 : fWidth(0)
64 , fWrapX(0)
65 , fHeight(0)
66 , fWrapY(0)
67 {}
68
69 bool operator==(const StitchData& other) const {
70 return fWidth == other.fWidth &&
71 fWrapX == other.fWrapX &&
72 fHeight == other.fHeight &&
73 fWrapY == other.fWrapY;
74 }
75
76 int fWidth; // How much to subtract to wrap for stitching.
77 int fWrapX; // Minimum value to wrap.
78 int fHeight;
79 int fWrapY;
80};
81
82struct SkPerlinNoiseShader::PaintingData {
83 PaintingData(const SkISize& tileSize)
84 : fSeed(0)
85 , fTileSize(tileSize)
86 , fPermutationsBitmap(NULL)
87 , fNoiseBitmap(NULL)
88 {}
89
90 ~PaintingData()
91 {
92 SkDELETE(fPermutationsBitmap);
93 SkDELETE(fNoiseBitmap);
94 }
95
96 int fSeed;
97 uint8_t fLatticeSelector[kBlockSize];
98 uint16_t fNoise[4][kBlockSize][2];
99 SkPoint fGradient[4][kBlockSize];
100 SkISize fTileSize;
101 SkVector fBaseFrequency;
102 StitchData fStitchDataInit;
103
104private:
105
106 SkBitmap* fPermutationsBitmap;
107 SkBitmap* fNoiseBitmap;
108
109public:
110
111 inline int random() {
112 static const int gRandAmplitude = 16807; // 7**5; primitive root of m
113 static const int gRandQ = 127773; // m / a
114 static const int gRandR = 2836; // m % a
115
116 int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
117 if (result <= 0)
118 result += kRandMaximum;
119 fSeed = result;
120 return result;
121 }
122
123 void init(SkScalar seed)
124 {
125 static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
126
senorblanco@chromium.org857e3202014-01-09 17:41:42 +0000127 // According to the SVG spec, we must truncate (not round) the seed value.
128 fSeed = SkScalarTruncToInt(seed);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000129 // The seed value clamp to the range [1, kRandMaximum - 1].
sugoi@google.come3b4c502013-04-05 13:47:09 +0000130 if (fSeed <= 0) {
131 fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
132 }
133 if (fSeed > kRandMaximum - 1) {
134 fSeed = kRandMaximum - 1;
135 }
136 for (int channel = 0; channel < 4; ++channel) {
137 for (int i = 0; i < kBlockSize; ++i) {
138 fLatticeSelector[i] = i;
139 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
140 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
141 }
142 }
143 for (int i = kBlockSize - 1; i > 0; --i) {
144 int k = fLatticeSelector[i];
145 int j = random() % kBlockSize;
146 SkASSERT(j >= 0);
147 SkASSERT(j < kBlockSize);
148 fLatticeSelector[i] = fLatticeSelector[j];
149 fLatticeSelector[j] = k;
150 }
151
152 // Perform the permutations now
153 {
154 // Copy noise data
155 uint16_t noise[4][kBlockSize][2];
156 for (int i = 0; i < kBlockSize; ++i) {
157 for (int channel = 0; channel < 4; ++channel) {
158 for (int j = 0; j < 2; ++j) {
159 noise[channel][i][j] = fNoise[channel][i][j];
160 }
161 }
162 }
163 // Do permutations on noise data
164 for (int i = 0; i < kBlockSize; ++i) {
165 for (int channel = 0; channel < 4; ++channel) {
166 for (int j = 0; j < 2; ++j) {
167 fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
168 }
169 }
170 }
171 }
172
173 // Half of the largest possible value for 16 bit unsigned int
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +0000174 static const SkScalar gHalfMax16bits = 32767.5f;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000175
176 // Compute gradients from permutated noise data
177 for (int channel = 0; channel < 4; ++channel) {
178 for (int i = 0; i < kBlockSize; ++i) {
179 fGradient[channel][i] = SkPoint::Make(
180 SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
181 gInvBlockSizef),
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000182 SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
sugoi@google.come3b4c502013-04-05 13:47:09 +0000183 gInvBlockSizef));
184 fGradient[channel][i].normalize();
185 // Put the normalized gradient back into the noise data
186 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000187 fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000188 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000189 fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000190 }
191 }
192
193 // Invalidate bitmaps
194 SkDELETE(fPermutationsBitmap);
195 fPermutationsBitmap = NULL;
196 SkDELETE(fNoiseBitmap);
197 fNoiseBitmap = NULL;
198 }
199
200 void stitch() {
201 SkScalar tileWidth = SkIntToScalar(fTileSize.width());
202 SkScalar tileHeight = SkIntToScalar(fTileSize.height());
203 SkASSERT(tileWidth > 0 && tileHeight > 0);
204 // When stitching tiled turbulence, the frequencies must be adjusted
205 // so that the tile borders will be continuous.
206 if (fBaseFrequency.fX) {
reed@google.com8015cdd2013-12-18 15:49:32 +0000207 SkScalar lowFrequencx =
208 SkScalarFloorToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
209 SkScalar highFrequencx =
210 SkScalarCeilToScalar(tileWidth * fBaseFrequency.fX) / tileWidth;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000211 // BaseFrequency should be non-negative according to the standard.
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000212 if (SkScalarDiv(fBaseFrequency.fX, lowFrequencx) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000213 SkScalarDiv(highFrequencx, fBaseFrequency.fX)) {
214 fBaseFrequency.fX = lowFrequencx;
215 } else {
216 fBaseFrequency.fX = highFrequencx;
217 }
218 }
219 if (fBaseFrequency.fY) {
reed@google.com8015cdd2013-12-18 15:49:32 +0000220 SkScalar lowFrequency =
221 SkScalarFloorToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
222 SkScalar highFrequency =
223 SkScalarCeilToScalar(tileHeight * fBaseFrequency.fY) / tileHeight;
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000224 if (SkScalarDiv(fBaseFrequency.fY, lowFrequency) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000225 SkScalarDiv(highFrequency, fBaseFrequency.fY)) {
226 fBaseFrequency.fY = lowFrequency;
227 } else {
228 fBaseFrequency.fY = highFrequency;
229 }
230 }
231 // Set up TurbulenceInitial stitch values.
232 fStitchDataInit.fWidth =
reed@google.com8015cdd2013-12-18 15:49:32 +0000233 SkScalarRoundToInt(tileWidth * fBaseFrequency.fX);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000234 fStitchDataInit.fWrapX = kPerlinNoise + fStitchDataInit.fWidth;
235 fStitchDataInit.fHeight =
reed@google.com8015cdd2013-12-18 15:49:32 +0000236 SkScalarRoundToInt(tileHeight * fBaseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000237 fStitchDataInit.fWrapY = kPerlinNoise + fStitchDataInit.fHeight;
238 }
239
240 SkBitmap* getPermutationsBitmap()
241 {
242 if (!fPermutationsBitmap) {
243 fPermutationsBitmap = SkNEW(SkBitmap);
244 fPermutationsBitmap->setConfig(SkBitmap::kA8_Config, kBlockSize, 1);
245 fPermutationsBitmap->allocPixels();
246 uint8_t* bitmapPixels = fPermutationsBitmap->getAddr8(0, 0);
247 memcpy(bitmapPixels, fLatticeSelector, sizeof(uint8_t) * kBlockSize);
248 }
249 return fPermutationsBitmap;
250 }
251
252 SkBitmap* getNoiseBitmap()
253 {
254 if (!fNoiseBitmap) {
255 fNoiseBitmap = SkNEW(SkBitmap);
256 fNoiseBitmap->setConfig(SkBitmap::kARGB_8888_Config, kBlockSize, 4);
257 fNoiseBitmap->allocPixels();
258 uint32_t* bitmapPixels = fNoiseBitmap->getAddr32(0, 0);
259 memcpy(bitmapPixels, fNoise[0][0], sizeof(uint16_t) * kBlockSize * 4 * 2);
260 }
261 return fNoiseBitmap;
262 }
263};
264
265SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
266 int numOctaves, SkScalar seed,
267 const SkISize* tileSize) {
268 return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY,
269 numOctaves, seed, tileSize));
270}
271
272SkShader* SkPerlinNoiseShader::CreateTubulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
273 int numOctaves, SkScalar seed,
274 const SkISize* tileSize) {
275 return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY,
276 numOctaves, seed, tileSize));
277}
278
279SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
280 SkScalar baseFrequencyX,
281 SkScalar baseFrequencyY,
282 int numOctaves,
283 SkScalar seed,
284 const SkISize* tileSize)
285 : fType(type)
286 , fBaseFrequencyX(baseFrequencyX)
287 , fBaseFrequencyY(baseFrequencyY)
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +0000288 , fNumOctaves(numOctaves > 255 ? 255 : numOctaves/*[0,255] octaves allowed*/)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000289 , fSeed(seed)
290 , fStitchTiles((tileSize != NULL) && !tileSize->isEmpty())
291 , fPaintingData(NULL)
292{
293 SkASSERT(numOctaves >= 0 && numOctaves < 256);
294 setTileSize(fStitchTiles ? *tileSize : SkISize::Make(0,0));
295 fMatrix.reset();
296}
297
298SkPerlinNoiseShader::SkPerlinNoiseShader(SkFlattenableReadBuffer& buffer) :
299 INHERITED(buffer), fPaintingData(NULL) {
300 fType = (SkPerlinNoiseShader::Type) buffer.readInt();
301 fBaseFrequencyX = buffer.readScalar();
302 fBaseFrequencyY = buffer.readScalar();
303 fNumOctaves = buffer.readInt();
304 fSeed = buffer.readScalar();
305 fStitchTiles = buffer.readBool();
306 fTileSize.fWidth = buffer.readInt();
307 fTileSize.fHeight = buffer.readInt();
308 setTileSize(fTileSize);
309 fMatrix.reset();
commit-bot@chromium.orgce33d602013-11-25 21:46:31 +0000310 buffer.validate(perlin_noise_type_is_valid(fType) &&
311 (fNumOctaves >= 0) && (fNumOctaves <= 255));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000312}
313
314SkPerlinNoiseShader::~SkPerlinNoiseShader() {
315 // Safety, should have been done in endContext()
316 SkDELETE(fPaintingData);
317}
318
319void SkPerlinNoiseShader::flatten(SkFlattenableWriteBuffer& buffer) const {
320 this->INHERITED::flatten(buffer);
321 buffer.writeInt((int) fType);
322 buffer.writeScalar(fBaseFrequencyX);
323 buffer.writeScalar(fBaseFrequencyY);
324 buffer.writeInt(fNumOctaves);
325 buffer.writeScalar(fSeed);
326 buffer.writeBool(fStitchTiles);
327 buffer.writeInt(fTileSize.fWidth);
328 buffer.writeInt(fTileSize.fHeight);
329}
330
331void SkPerlinNoiseShader::initPaint(PaintingData& paintingData)
332{
333 paintingData.init(fSeed);
334
335 // Set frequencies to original values
336 paintingData.fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
337 // Adjust frequecies based on size if stitching is enabled
338 if (fStitchTiles) {
339 paintingData.stitch();
340 }
341}
342
343void SkPerlinNoiseShader::setTileSize(const SkISize& tileSize) {
344 fTileSize = tileSize;
345
346 if (NULL == fPaintingData) {
347 fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize));
348 initPaint(*fPaintingData);
349 } else {
350 // Set Size
351 fPaintingData->fTileSize = fTileSize;
352 // Set frequencies to original values
353 fPaintingData->fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
354 // Adjust frequecies based on size if stitching is enabled
355 if (fStitchTiles) {
356 fPaintingData->stitch();
357 }
358 }
359}
360
361SkScalar SkPerlinNoiseShader::noise2D(int channel, const PaintingData& paintingData,
362 const StitchData& stitchData, const SkPoint& noiseVector)
363{
364 struct Noise {
365 int noisePositionIntegerValue;
366 SkScalar noisePositionFractionValue;
367 Noise(SkScalar component)
368 {
369 SkScalar position = component + kPerlinNoise;
370 noisePositionIntegerValue = SkScalarFloorToInt(position);
371 noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
372 }
373 };
374 Noise noiseX(noiseVector.x());
375 Noise noiseY(noiseVector.y());
376 SkScalar u, v;
377 // If stitching, adjust lattice points accordingly.
378 if (fStitchTiles) {
379 noiseX.noisePositionIntegerValue =
380 checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
381 noiseY.noisePositionIntegerValue =
382 checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
383 }
384 noiseX.noisePositionIntegerValue &= kBlockMask;
385 noiseY.noisePositionIntegerValue &= kBlockMask;
386 int latticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000387 paintingData.fLatticeSelector[noiseX.noisePositionIntegerValue] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000388 noiseY.noisePositionIntegerValue;
389 int nextLatticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000390 paintingData.fLatticeSelector[(noiseX.noisePositionIntegerValue + 1) & kBlockMask] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000391 noiseY.noisePositionIntegerValue;
392 SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
393 SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
394 // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
395 SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
396 noiseY.noisePositionFractionValue); // Offset (0,0)
397 u = paintingData.fGradient[channel][latticeIndex & kBlockMask].dot(fractionValue);
398 fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
399 v = paintingData.fGradient[channel][nextLatticeIndex & kBlockMask].dot(fractionValue);
400 SkScalar a = SkScalarInterp(u, v, sx);
401 fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
402 v = paintingData.fGradient[channel][(nextLatticeIndex + 1) & kBlockMask].dot(fractionValue);
403 fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
404 u = paintingData.fGradient[channel][(latticeIndex + 1) & kBlockMask].dot(fractionValue);
405 SkScalar b = SkScalarInterp(u, v, sx);
406 return SkScalarInterp(a, b, sy);
407}
408
409SkScalar SkPerlinNoiseShader::calculateTurbulenceValueForPoint(
410 int channel, const PaintingData& paintingData, StitchData& stitchData, const SkPoint& point)
411{
412 if (fStitchTiles) {
413 // Set up TurbulenceInitial stitch values.
414 stitchData = paintingData.fStitchDataInit;
415 }
416 SkScalar turbulenceFunctionResult = 0;
417 SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), paintingData.fBaseFrequency.fX),
418 SkScalarMul(point.y(), paintingData.fBaseFrequency.fY)));
419 SkScalar ratio = SK_Scalar1;
420 for (int octave = 0; octave < fNumOctaves; ++octave) {
421 SkScalar noise = noise2D(channel, paintingData, stitchData, noiseVector);
422 turbulenceFunctionResult += SkScalarDiv(
423 (fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio);
424 noiseVector.fX *= 2;
425 noiseVector.fY *= 2;
426 ratio *= 2;
427 if (fStitchTiles) {
428 // Update stitch values
429 stitchData.fWidth *= 2;
430 stitchData.fWrapX = stitchData.fWidth + kPerlinNoise;
431 stitchData.fHeight *= 2;
432 stitchData.fWrapY = stitchData.fHeight + kPerlinNoise;
433 }
434 }
435
436 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
437 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
438 if (fType == kFractalNoise_Type) {
439 turbulenceFunctionResult =
440 SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
441 }
442
443 if (channel == 3) { // Scale alpha by paint value
444 turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult,
445 SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255)));
446 }
447
448 // Clamp result
449 return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
450}
451
452SkPMColor SkPerlinNoiseShader::shade(const SkPoint& point, StitchData& stitchData) {
453 SkMatrix matrix = fMatrix;
454 SkMatrix invMatrix;
455 if (!matrix.invert(&invMatrix)) {
456 invMatrix.reset();
457 } else {
458 invMatrix.postConcat(invMatrix); // Square the matrix
459 }
460 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
461 // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
462 matrix.postTranslate(SK_Scalar1, SK_Scalar1);
463 SkPoint newPoint;
464 matrix.mapPoints(&newPoint, &point, 1);
465 invMatrix.mapPoints(&newPoint, &newPoint, 1);
466 newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
467 newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
468
469 U8CPU rgba[4];
470 for (int channel = 3; channel >= 0; --channel) {
471 rgba[channel] = SkScalarFloorToInt(255 *
472 calculateTurbulenceValueForPoint(channel, *fPaintingData, stitchData, newPoint));
473 }
474 return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
475}
476
477bool SkPerlinNoiseShader::setContext(const SkBitmap& device, const SkPaint& paint,
478 const SkMatrix& matrix) {
479 fMatrix = matrix;
480 return INHERITED::setContext(device, paint, matrix);
481}
482
483void SkPerlinNoiseShader::shadeSpan(int x, int y, SkPMColor result[], int count) {
484 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
485 StitchData stitchData;
486 for (int i = 0; i < count; ++i) {
487 result[i] = shade(point, stitchData);
488 point.fX += SK_Scalar1;
489 }
490}
491
492void SkPerlinNoiseShader::shadeSpan16(int x, int y, uint16_t result[], int count) {
493 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
494 StitchData stitchData;
495 DITHER_565_SCAN(y);
496 for (int i = 0; i < count; ++i) {
497 unsigned dither = DITHER_VALUE(x);
498 result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
499 DITHER_INC_X(x);
500 point.fX += SK_Scalar1;
501 }
502}
503
504/////////////////////////////////////////////////////////////////////
505
commit-bot@chromium.org344cf452013-06-17 14:19:01 +0000506#if SK_SUPPORT_GPU
sugoi@google.come3b4c502013-04-05 13:47:09 +0000507
508#include "GrTBackendEffectFactory.h"
509
sugoi@google.com4775cba2013-04-17 13:46:56 +0000510class GrGLNoise : public GrGLEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000511public:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000512 GrGLNoise(const GrBackendEffectFactory& factory,
513 const GrDrawEffect& drawEffect);
514 virtual ~GrGLNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000515
sugoi@google.com4775cba2013-04-17 13:46:56 +0000516 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
517
518 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
519
520protected:
521 SkPerlinNoiseShader::Type fType;
522 bool fStitchTiles;
523 int fNumOctaves;
524 GrGLUniformManager::UniformHandle fBaseFrequencyUni;
525 GrGLUniformManager::UniformHandle fAlphaUni;
526 GrGLUniformManager::UniformHandle fInvMatrixUni;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000527
528private:
529 typedef GrGLEffect INHERITED;
530};
531
532class GrGLPerlinNoise : public GrGLNoise {
533public:
sugoi@google.come3b4c502013-04-05 13:47:09 +0000534 GrGLPerlinNoise(const GrBackendEffectFactory& factory,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000535 const GrDrawEffect& drawEffect)
536 : GrGLNoise(factory, drawEffect) {}
537 virtual ~GrGLPerlinNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000538
539 virtual void emitCode(GrGLShaderBuilder*,
540 const GrDrawEffect&,
541 EffectKey,
542 const char* outputColor,
543 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000544 const TransformedCoordsArray&,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000545 const TextureSamplerArray&) SK_OVERRIDE;
546
sugoi@google.com4775cba2013-04-17 13:46:56 +0000547 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000548
549private:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000550 GrGLUniformManager::UniformHandle fStitchDataUni;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000551
sugoi@google.com4775cba2013-04-17 13:46:56 +0000552 typedef GrGLNoise INHERITED;
553};
554
555class GrGLSimplexNoise : public GrGLNoise {
556 // Note : This is for reference only. GrGLPerlinNoise is used for processing.
557public:
558 GrGLSimplexNoise(const GrBackendEffectFactory& factory,
559 const GrDrawEffect& drawEffect)
560 : GrGLNoise(factory, drawEffect) {}
561
562 virtual ~GrGLSimplexNoise() {}
563
564 virtual void emitCode(GrGLShaderBuilder*,
565 const GrDrawEffect&,
566 EffectKey,
567 const char* outputColor,
568 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000569 const TransformedCoordsArray&,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000570 const TextureSamplerArray&) SK_OVERRIDE;
571
572 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
573
574private:
575 GrGLUniformManager::UniformHandle fSeedUni;
576
577 typedef GrGLNoise INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000578};
579
580/////////////////////////////////////////////////////////////////////
581
sugoi@google.com4775cba2013-04-17 13:46:56 +0000582class GrNoiseEffect : public GrEffect {
583public:
584 virtual ~GrNoiseEffect() { }
585
586 SkPerlinNoiseShader::Type type() const { return fType; }
587 bool stitchTiles() const { return fStitchTiles; }
588 const SkVector& baseFrequency() const { return fBaseFrequency; }
589 int numOctaves() const { return fNumOctaves; }
bsalomon@google.com77af6802013-10-02 13:04:56 +0000590 const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000591 uint8_t alpha() const { return fAlpha; }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000592
593 void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE {
594 *validFlags = 0; // This is noise. Nothing is constant.
595 }
596
597protected:
598 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
599 const GrNoiseEffect& s = CastEffect<GrNoiseEffect>(sBase);
600 return fType == s.fType &&
601 fBaseFrequency == s.fBaseFrequency &&
602 fNumOctaves == s.fNumOctaves &&
603 fStitchTiles == s.fStitchTiles &&
bsalomon@google.com77af6802013-10-02 13:04:56 +0000604 fCoordTransform.getMatrix() == s.fCoordTransform.getMatrix() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000605 fAlpha == s.fAlpha;
606 }
607
608 GrNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, int numOctaves,
609 bool stitchTiles, const SkMatrix& matrix, uint8_t alpha)
610 : fType(type)
611 , fBaseFrequency(baseFrequency)
612 , fNumOctaves(numOctaves)
613 , fStitchTiles(stitchTiles)
614 , fMatrix(matrix)
615 , fAlpha(alpha) {
bsalomon@google.com77af6802013-10-02 13:04:56 +0000616 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
617 // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions.
618 SkMatrix m = matrix;
619 m.postTranslate(SK_Scalar1, SK_Scalar1);
620 fCoordTransform.reset(kLocal_GrCoordSet, m);
621 this->addCoordTransform(&fCoordTransform);
commit-bot@chromium.orga34995e2013-10-23 05:42:03 +0000622 this->setWillNotUseInputColor();
sugoi@google.com4775cba2013-04-17 13:46:56 +0000623 }
624
625 SkPerlinNoiseShader::Type fType;
bsalomon@google.com77af6802013-10-02 13:04:56 +0000626 GrCoordTransform fCoordTransform;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000627 SkVector fBaseFrequency;
628 int fNumOctaves;
629 bool fStitchTiles;
630 SkMatrix fMatrix;
631 uint8_t fAlpha;
632
633private:
634 typedef GrEffect INHERITED;
635};
636
637class GrPerlinNoiseEffect : public GrNoiseEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000638public:
639 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
640 int numOctaves, bool stitchTiles,
641 const SkPerlinNoiseShader::StitchData& stitchData,
642 GrTexture* permutationsTexture, GrTexture* noiseTexture,
643 const SkMatrix& matrix, uint8_t alpha) {
644 AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves,
645 stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha)));
646 return CreateEffectRef(effect);
647 }
648
649 virtual ~GrPerlinNoiseEffect() { }
650
651 static const char* Name() { return "PerlinNoise"; }
652 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
653 return GrTBackendEffectFactory<GrPerlinNoiseEffect>::getInstance();
654 }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000655 const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000656
657 typedef GrGLPerlinNoise GLEffect;
658
sugoi@google.come3b4c502013-04-05 13:47:09 +0000659private:
660 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
661 const GrPerlinNoiseEffect& s = CastEffect<GrPerlinNoiseEffect>(sBase);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000662 return INHERITED::onIsEqual(sBase) &&
663 fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() &&
sugoi@google.come3b4c502013-04-05 13:47:09 +0000664 fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000665 fStitchData == s.fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000666 }
667
668 GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
669 int numOctaves, bool stitchTiles,
670 const SkPerlinNoiseShader::StitchData& stitchData,
671 GrTexture* permutationsTexture, GrTexture* noiseTexture,
672 const SkMatrix& matrix, uint8_t alpha)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000673 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
674 , fPermutationsAccess(permutationsTexture)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000675 , fNoiseAccess(noiseTexture)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000676 , fStitchData(stitchData) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000677 this->addTextureAccess(&fPermutationsAccess);
678 this->addTextureAccess(&fNoiseAccess);
679 }
680
sugoi@google.com4775cba2013-04-17 13:46:56 +0000681 GR_DECLARE_EFFECT_TEST;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000682
683 GrTextureAccess fPermutationsAccess;
684 GrTextureAccess fNoiseAccess;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000685 SkPerlinNoiseShader::StitchData fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000686
sugoi@google.com4775cba2013-04-17 13:46:56 +0000687 typedef GrNoiseEffect INHERITED;
688};
689
690class GrSimplexNoiseEffect : public GrNoiseEffect {
691 // Note : This is for reference only. GrPerlinNoiseEffect is used for processing.
692public:
693 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
694 int numOctaves, bool stitchTiles, const SkScalar seed,
695 const SkMatrix& matrix, uint8_t alpha) {
696 AutoEffectUnref effect(SkNEW_ARGS(GrSimplexNoiseEffect, (type, baseFrequency, numOctaves,
697 stitchTiles, seed, matrix, alpha)));
698 return CreateEffectRef(effect);
699 }
700
701 virtual ~GrSimplexNoiseEffect() { }
702
703 static const char* Name() { return "SimplexNoise"; }
704 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
705 return GrTBackendEffectFactory<GrSimplexNoiseEffect>::getInstance();
706 }
707 const SkScalar& seed() const { return fSeed; }
708
709 typedef GrGLSimplexNoise GLEffect;
710
711private:
712 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
713 const GrSimplexNoiseEffect& s = CastEffect<GrSimplexNoiseEffect>(sBase);
714 return INHERITED::onIsEqual(sBase) && fSeed == s.fSeed;
715 }
716
717 GrSimplexNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
718 int numOctaves, bool stitchTiles, const SkScalar seed,
719 const SkMatrix& matrix, uint8_t alpha)
720 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
721 , fSeed(seed) {
722 }
723
724 SkScalar fSeed;
725
726 typedef GrNoiseEffect INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000727};
728
729/////////////////////////////////////////////////////////////////////
sugoi@google.come3b4c502013-04-05 13:47:09 +0000730GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect);
731
commit-bot@chromium.orge0e7cfe2013-09-09 20:09:12 +0000732GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkRandom* random,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000733 GrContext* context,
734 const GrDrawTargetCaps&,
735 GrTexture**) {
sugoi@google.com423ac132013-04-18 14:04:57 +0000736 int numOctaves = random->nextRangeU(2, 10);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000737 bool stitchTiles = random->nextBool();
738 SkScalar seed = SkIntToScalar(random->nextU());
739 SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +0000740 SkScalar baseFrequencyX = random->nextRangeScalar(0.01f,
741 0.99f);
742 SkScalar baseFrequencyY = random->nextRangeScalar(0.01f,
743 0.99f);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000744
745 SkShader* shader = random->nextBool() ?
746 SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
747 stitchTiles ? &tileSize : NULL) :
748 SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
749 stitchTiles ? &tileSize : NULL);
750
751 SkPaint paint;
752 GrEffectRef* effect = shader->asNewEffect(context, paint);
753
754 SkDELETE(shader);
755
756 return effect;
757}
sugoi@google.com4775cba2013-04-17 13:46:56 +0000758
sugoi@google.come3b4c502013-04-05 13:47:09 +0000759/////////////////////////////////////////////////////////////////////
760
sugoi@google.com4775cba2013-04-17 13:46:56 +0000761void GrGLSimplexNoise::emitCode(GrGLShaderBuilder* builder,
762 const GrDrawEffect&,
763 EffectKey key,
764 const char* outputColor,
765 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000766 const TransformedCoordsArray& coords,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000767 const TextureSamplerArray&) {
768 sk_ignore_unused_variable(inputColor);
769
bsalomon@google.com77af6802013-10-02 13:04:56 +0000770 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000771
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000772 fSeedUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000773 kFloat_GrSLType, "seed");
774 const char* seedUni = builder->getUniformCStr(fSeedUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000775 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000776 kMat33f_GrSLType, "invMatrix");
777 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000778 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000779 kVec2f_GrSLType, "baseFrequency");
780 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000781 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000782 kFloat_GrSLType, "alpha");
783 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
784
785 // Add vec3 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000786 static const GrGLShaderVar gVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000787 GrGLShaderVar("x", kVec3f_GrSLType)
788 };
789
790 SkString mod289_3_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000791 builder->fsEmitFunction(kVec3f_GrSLType,
792 "mod289", SK_ARRAY_COUNT(gVec3Args), gVec3Args,
793 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
794 "return x - floor(x * C.xxx) * C.yyy;", &mod289_3_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000795
796 // Add vec4 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000797 static const GrGLShaderVar gVec4Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000798 GrGLShaderVar("x", kVec4f_GrSLType)
799 };
800
801 SkString mod289_4_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000802 builder->fsEmitFunction(kVec4f_GrSLType,
803 "mod289", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
804 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
805 "return x - floor(x * C.xxxx) * C.yyyy;", &mod289_4_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000806
807 // Add vec4 permute function
sugoi@google.comd537af52013-06-10 13:59:25 +0000808 SkString permuteCode;
809 permuteCode.appendf("const vec2 C = vec2(34.0, 1.0);\n"
810 "return %s(((x * C.xxxx) + C.yyyy) * x);", mod289_4_funcName.c_str());
811 SkString permuteFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000812 builder->fsEmitFunction(kVec4f_GrSLType,
813 "permute", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
814 permuteCode.c_str(), &permuteFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000815
816 // Add vec4 taylorInvSqrt function
sugoi@google.comd537af52013-06-10 13:59:25 +0000817 SkString taylorInvSqrtFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000818 builder->fsEmitFunction(kVec4f_GrSLType,
819 "taylorInvSqrt", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
820 "const vec2 C = vec2(-0.85373472095314, 1.79284291400159);\n"
821 "return x * C.xxxx + C.yyyy;", &taylorInvSqrtFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000822
823 // Add vec3 noise function
sugoi@google.comd537af52013-06-10 13:59:25 +0000824 static const GrGLShaderVar gNoiseVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000825 GrGLShaderVar("v", kVec3f_GrSLType)
826 };
827
sugoi@google.comd537af52013-06-10 13:59:25 +0000828 SkString noiseCode;
829 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000830 "const vec2 C = vec2(1.0/6.0, 1.0/3.0);\n"
831 "const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n"
832
833 // First corner
834 "vec3 i = floor(v + dot(v, C.yyy));\n"
835 "vec3 x0 = v - i + dot(i, C.xxx);\n"
836
837 // Other corners
838 "vec3 g = step(x0.yzx, x0.xyz);\n"
839 "vec3 l = 1.0 - g;\n"
840 "vec3 i1 = min(g.xyz, l.zxy);\n"
841 "vec3 i2 = max(g.xyz, l.zxy);\n"
842
843 "vec3 x1 = x0 - i1 + C.xxx;\n"
844 "vec3 x2 = x0 - i2 + C.yyy;\n" // 2.0*C.x = 1/3 = C.y
845 "vec3 x3 = x0 - D.yyy;\n" // -1.0+3.0*C.x = -0.5 = -D.y
846 );
847
sugoi@google.comd537af52013-06-10 13:59:25 +0000848 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000849 // Permutations
850 "i = %s(i);\n"
851 "vec4 p = %s(%s(%s(\n"
852 " i.z + vec4(0.0, i1.z, i2.z, 1.0)) +\n"
853 " i.y + vec4(0.0, i1.y, i2.y, 1.0)) +\n"
854 " i.x + vec4(0.0, i1.x, i2.x, 1.0));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000855 mod289_3_funcName.c_str(), permuteFuncName.c_str(), permuteFuncName.c_str(),
856 permuteFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000857
sugoi@google.comd537af52013-06-10 13:59:25 +0000858 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000859 // Gradients: 7x7 points over a square, mapped onto an octahedron.
860 // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
861 "float n_ = 0.142857142857;\n" // 1.0/7.0
862 "vec3 ns = n_ * D.wyz - D.xzx;\n"
863
864 "vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\n" // mod(p,7*7)
865
866 "vec4 x_ = floor(j * ns.z);\n"
867 "vec4 y_ = floor(j - 7.0 * x_);" // mod(j,N)
868
869 "vec4 x = x_ *ns.x + ns.yyyy;\n"
870 "vec4 y = y_ *ns.x + ns.yyyy;\n"
871 "vec4 h = 1.0 - abs(x) - abs(y);\n"
872
873 "vec4 b0 = vec4(x.xy, y.xy);\n"
874 "vec4 b1 = vec4(x.zw, y.zw);\n"
875 );
876
sugoi@google.comd537af52013-06-10 13:59:25 +0000877 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000878 "vec4 s0 = floor(b0) * 2.0 + 1.0;\n"
879 "vec4 s1 = floor(b1) * 2.0 + 1.0;\n"
880 "vec4 sh = -step(h, vec4(0.0));\n"
881
882 "vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;\n"
883 "vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;\n"
884
885 "vec3 p0 = vec3(a0.xy, h.x);\n"
886 "vec3 p1 = vec3(a0.zw, h.y);\n"
887 "vec3 p2 = vec3(a1.xy, h.z);\n"
888 "vec3 p3 = vec3(a1.zw, h.w);\n"
889 );
890
sugoi@google.comd537af52013-06-10 13:59:25 +0000891 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000892 // Normalise gradients
893 "vec4 norm = %s(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n"
894 "p0 *= norm.x;\n"
895 "p1 *= norm.y;\n"
896 "p2 *= norm.z;\n"
897 "p3 *= norm.w;\n"
898
899 // Mix final noise value
900 "vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n"
901 "m = m * m;\n"
902 "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 +0000903 taylorInvSqrtFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000904
sugoi@google.comd537af52013-06-10 13:59:25 +0000905 SkString noiseFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000906 builder->fsEmitFunction(kFloat_GrSLType,
907 "snoise", SK_ARRAY_COUNT(gNoiseVec3Args), gNoiseVec3Args,
908 noiseCode.c_str(), &noiseFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000909
910 const char* noiseVecIni = "noiseVecIni";
911 const char* factors = "factors";
912 const char* sum = "sum";
913 const char* xOffsets = "xOffsets";
914 const char* yOffsets = "yOffsets";
915 const char* channel = "channel";
916
917 // Fill with some prime numbers
918 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(13.0, 53.0, 101.0, 151.0);\n", xOffsets);
919 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(109.0, 167.0, 23.0, 67.0);\n", yOffsets);
920
921 // There are rounding errors if the floor operation is not performed here
922 builder->fsCodeAppendf(
923 "\t\tvec3 %s = vec3(floor((%s*vec3(%s, 1.0)).xy) * vec2(0.66) * %s, 0.0);\n",
commit-bot@chromium.org7ab7ca42013-08-28 15:59:13 +0000924 noiseVecIni, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000925
926 // Perturb the texcoords with three components of noise
927 builder->fsCodeAppendf("\t\t%s += 0.1 * vec3(%s(%s + vec3( 0.0, 0.0, %s)),"
928 "%s(%s + vec3( 43.0, 17.0, %s)),"
929 "%s(%s + vec3(-17.0, -43.0, %s)));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000930 noiseVecIni, noiseFuncName.c_str(), noiseVecIni, seedUni,
931 noiseFuncName.c_str(), noiseVecIni, seedUni,
932 noiseFuncName.c_str(), noiseVecIni, seedUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000933
934 builder->fsCodeAppendf("\t\t%s = vec4(0.0);\n", outputColor);
935
936 builder->fsCodeAppendf("\t\tvec3 %s = vec3(1.0);\n", factors);
937 builder->fsCodeAppendf("\t\tfloat %s = 0.0;\n", sum);
938
939 // Loop over all octaves
940 builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {\n", fNumOctaves);
941
942 // Loop over the 4 channels
943 builder->fsCodeAppendf("\t\t\tfor (int %s = 3; %s >= 0; --%s) {\n", channel, channel, channel);
944
945 builder->fsCodeAppendf(
946 "\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 +0000947 outputColor, factors, noiseFuncName.c_str(), noiseVecIni, factors, xOffsets, channel,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000948 yOffsets, channel, seedUni, factors);
949
950 builder->fsCodeAppend("\t\t\t}\n"); // end of the for loop on channels
951
952 builder->fsCodeAppendf("\t\t\t%s += %s.x;\n", sum, factors);
953 builder->fsCodeAppendf("\t\t\t%s *= vec3(0.5, 2.0, 0.75);\n", factors);
954
955 builder->fsCodeAppend("\t\t}\n"); // end of the for loop on octaves
956
957 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
958 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
959 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
960 builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5 / %s) + vec4(0.5);\n",
961 outputColor, outputColor, sum);
962 } else {
963 builder->fsCodeAppendf("\t\t%s = abs(%s / vec4(%s));\n",
964 outputColor, outputColor, sum);
965 }
966
967 builder->fsCodeAppendf("\t\t%s.a *= %s;\n", outputColor, alphaUni);
968
969 // Clamp values
970 builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);\n", outputColor, outputColor);
971
972 // Pre-multiply the result
973 builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
974 outputColor, outputColor, outputColor, outputColor);
975}
976
sugoi@google.come3b4c502013-04-05 13:47:09 +0000977void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder,
978 const GrDrawEffect&,
979 EffectKey key,
980 const char* outputColor,
981 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000982 const TransformedCoordsArray& coords,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000983 const TextureSamplerArray& samplers) {
984 sk_ignore_unused_variable(inputColor);
985
bsalomon@google.com77af6802013-10-02 13:04:56 +0000986 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000987
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000988 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000989 kMat33f_GrSLType, "invMatrix");
990 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000991 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000992 kVec2f_GrSLType, "baseFrequency");
993 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000994 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000995 kFloat_GrSLType, "alpha");
996 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
997
998 const char* stitchDataUni = NULL;
999 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001000 fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001001 kVec2f_GrSLType, "stitchData");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001002 stitchDataUni = builder->getUniformCStr(fStitchDataUni);
1003 }
1004
sugoi@google.comd537af52013-06-10 13:59:25 +00001005 // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
1006 const char* chanCoordR = "0.125";
1007 const char* chanCoordG = "0.375";
1008 const char* chanCoordB = "0.625";
1009 const char* chanCoordA = "0.875";
1010 const char* chanCoord = "chanCoord";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001011 const char* stitchData = "stitchData";
1012 const char* ratio = "ratio";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001013 const char* noiseXY = "noiseXY";
1014 const char* noiseVec = "noiseVec";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001015 const char* noiseSmooth = "noiseSmooth";
1016 const char* fractVal = "fractVal";
1017 const char* uv = "uv";
1018 const char* ab = "ab";
1019 const char* latticeIdx = "latticeIdx";
1020 const char* lattice = "lattice";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001021 const char* inc8bit = "0.00390625"; // 1.0 / 256.0
1022 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
1023 // [-1,1] vector and perform a dot product between that vector and the provided vector.
1024 const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
1025
sugoi@google.comd537af52013-06-10 13:59:25 +00001026 // Add noise function
1027 static const GrGLShaderVar gPerlinNoiseArgs[] = {
1028 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001029 GrGLShaderVar(noiseVec, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001030 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001031
sugoi@google.comd537af52013-06-10 13:59:25 +00001032 static const GrGLShaderVar gPerlinNoiseStitchArgs[] = {
1033 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001034 GrGLShaderVar(noiseVec, kVec2f_GrSLType),
1035 GrGLShaderVar(stitchData, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001036 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001037
sugoi@google.comd537af52013-06-10 13:59:25 +00001038 SkString noiseCode;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001039
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001040 noiseCode.appendf("\tvec4 %s = vec4(floor(%s), fract(%s));", noiseXY, noiseVec, noiseVec);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001041
1042 // smooth curve : t * t * (3 - 2 * t)
sugoi@google.comd537af52013-06-10 13:59:25 +00001043 noiseCode.appendf("\n\tvec2 %s = %s.zw * %s.zw * (vec2(3.0) - vec2(2.0) * %s.zw);",
1044 noiseSmooth, noiseXY, noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001045
1046 // Adjust frequencies if we're stitching tiles
1047 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001048 noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001049 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001050 noiseCode.appendf("\n\tif(%s.x >= (%s.x - 1.0)) { %s.x -= (%s.x - 1.0); }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001051 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001052 noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001053 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001054 noiseCode.appendf("\n\tif(%s.y >= (%s.y - 1.0)) { %s.y -= (%s.y - 1.0); }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001055 noiseXY, stitchData, noiseXY, stitchData);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001056 }
1057
1058 // Get texture coordinates and normalize
sugoi@google.comd537af52013-06-10 13:59:25 +00001059 noiseCode.appendf("\n\t%s.xy = fract(floor(mod(%s.xy, 256.0)) / vec2(256.0));\n",
1060 noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001061
1062 // Get permutation for x
1063 {
1064 SkString xCoords("");
1065 xCoords.appendf("vec2(%s.x, 0.5)", noiseXY);
1066
sugoi@google.comd537af52013-06-10 13:59:25 +00001067 noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
1068 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1069 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001070 }
1071
1072 // Get permutation for x + 1
1073 {
1074 SkString xCoords("");
1075 xCoords.appendf("vec2(fract(%s.x + %s), 0.5)", noiseXY, inc8bit);
1076
sugoi@google.comd537af52013-06-10 13:59:25 +00001077 noiseCode.appendf("\n\t%s.y = ", latticeIdx);
1078 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1079 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001080 }
1081
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001082#if defined(SK_BUILD_FOR_ANDROID)
1083 // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
1084 // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
1085 // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
1086 // (or 0.484368 here). The following rounding operation prevents these precision issues from
1087 // affecting the result of the noise by making sure that we only have multiples of 1/255.
1088 // (Note that 1/255 is about 0.003921569, which is the value used here).
1089 noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);",
1090 latticeIdx, latticeIdx);
1091#endif
1092
sugoi@google.come3b4c502013-04-05 13:47:09 +00001093 // Get (x,y) coordinates with the permutated x
sugoi@google.comd537af52013-06-10 13:59:25 +00001094 noiseCode.appendf("\n\t%s = fract(%s + %s.yy);", latticeIdx, latticeIdx, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001095
sugoi@google.comd537af52013-06-10 13:59:25 +00001096 noiseCode.appendf("\n\tvec2 %s = %s.zw;", fractVal, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001097
sugoi@google.comd537af52013-06-10 13:59:25 +00001098 noiseCode.appendf("\n\n\tvec2 %s;", uv);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001099 // Compute u, at offset (0,0)
1100 {
1101 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001102 latticeCoords.appendf("vec2(%s.x, %s)", latticeIdx, chanCoord);
1103 noiseCode.appendf("\n\tvec4 %s = ", lattice);
1104 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1105 kVec2f_GrSLType);
1106 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1107 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001108 }
1109
sugoi@google.comd537af52013-06-10 13:59:25 +00001110 noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001111 // Compute v, at offset (-1,0)
1112 {
1113 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001114 latticeCoords.appendf("vec2(%s.y, %s)", latticeIdx, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001115 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001116 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1117 kVec2f_GrSLType);
1118 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1119 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001120 }
1121
1122 // Compute 'a' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001123 noiseCode.appendf("\n\tvec2 %s;", ab);
1124 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 +00001125
sugoi@google.comd537af52013-06-10 13:59:25 +00001126 noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001127 // Compute v, at offset (-1,-1)
1128 {
1129 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001130 latticeCoords.appendf("vec2(fract(%s.y + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001131 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001132 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1133 kVec2f_GrSLType);
1134 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1135 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001136 }
1137
sugoi@google.comd537af52013-06-10 13:59:25 +00001138 noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001139 // Compute u, at offset (0,-1)
1140 {
1141 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001142 latticeCoords.appendf("vec2(fract(%s.x + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001143 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001144 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1145 kVec2f_GrSLType);
1146 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1147 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001148 }
1149
1150 // Compute 'b' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001151 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 +00001152 // Compute the noise as a linear interpolation of 'a' and 'b'
sugoi@google.comd537af52013-06-10 13:59:25 +00001153 noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001154
sugoi@google.comd537af52013-06-10 13:59:25 +00001155 SkString noiseFuncName;
1156 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001157 builder->fsEmitFunction(kFloat_GrSLType,
1158 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
1159 gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001160 } else {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001161 builder->fsEmitFunction(kFloat_GrSLType,
1162 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
1163 gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001164 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001165
sugoi@google.comd537af52013-06-10 13:59:25 +00001166 // There are rounding errors if the floor operation is not performed here
1167 builder->fsCodeAppendf("\n\t\tvec2 %s = floor((%s * vec3(%s, 1.0)).xy) * %s;",
commit-bot@chromium.org7ab7ca42013-08-28 15:59:13 +00001168 noiseVec, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.comd537af52013-06-10 13:59:25 +00001169
1170 // Clear the color accumulator
1171 builder->fsCodeAppendf("\n\t\t%s = vec4(0.0);", outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001172
1173 if (fStitchTiles) {
sugoi@google.comd537af52013-06-10 13:59:25 +00001174 // Set up TurbulenceInitial stitch values.
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001175 builder->fsCodeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001176 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001177
sugoi@google.comd537af52013-06-10 13:59:25 +00001178 builder->fsCodeAppendf("\n\t\tfloat %s = 1.0;", ratio);
1179
1180 // Loop over all octaves
1181 builder->fsCodeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
1182
1183 builder->fsCodeAppendf("\n\t\t\t%s += ", outputColor);
1184 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1185 builder->fsCodeAppend("abs(");
1186 }
1187 if (fStitchTiles) {
1188 builder->fsCodeAppendf(
1189 "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
1190 "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
1191 noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
1192 noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
1193 noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
1194 noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
1195 } else {
1196 builder->fsCodeAppendf(
1197 "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
1198 "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
1199 noiseFuncName.c_str(), chanCoordR, noiseVec,
1200 noiseFuncName.c_str(), chanCoordG, noiseVec,
1201 noiseFuncName.c_str(), chanCoordB, noiseVec,
1202 noiseFuncName.c_str(), chanCoordA, noiseVec);
1203 }
1204 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1205 builder->fsCodeAppendf(")"); // end of "abs("
1206 }
1207 builder->fsCodeAppendf(" * %s;", ratio);
1208
1209 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
1210 builder->fsCodeAppendf("\n\t\t\t%s *= 0.5;", ratio);
1211
1212 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001213 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData);
sugoi@google.comd537af52013-06-10 13:59:25 +00001214 }
1215 builder->fsCodeAppend("\n\t\t}"); // end of the for loop on octaves
sugoi@google.come3b4c502013-04-05 13:47:09 +00001216
1217 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
1218 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
1219 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
sugoi@google.comd537af52013-06-10 13:59:25 +00001220 builder->fsCodeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001221 }
1222
sugoi@google.comd537af52013-06-10 13:59:25 +00001223 builder->fsCodeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001224
1225 // Clamp values
sugoi@google.comd537af52013-06-10 13:59:25 +00001226 builder->fsCodeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001227
1228 // Pre-multiply the result
sugoi@google.comd537af52013-06-10 13:59:25 +00001229 builder->fsCodeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
sugoi@google.come3b4c502013-04-05 13:47:09 +00001230 outputColor, outputColor, outputColor, outputColor);
1231}
1232
sugoi@google.com4775cba2013-04-17 13:46:56 +00001233GrGLNoise::GrGLNoise(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect)
sugoi@google.come3b4c502013-04-05 13:47:09 +00001234 : INHERITED (factory)
1235 , fType(drawEffect.castEffect<GrPerlinNoiseEffect>().type())
1236 , fStitchTiles(drawEffect.castEffect<GrPerlinNoiseEffect>().stitchTiles())
bsalomon@google.com77af6802013-10-02 13:04:56 +00001237 , fNumOctaves(drawEffect.castEffect<GrPerlinNoiseEffect>().numOctaves()) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001238}
1239
sugoi@google.com4775cba2013-04-17 13:46:56 +00001240GrGLEffect::EffectKey GrGLNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001241 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1242
1243 EffectKey key = turbulence.numOctaves();
1244
1245 key = key << 3; // Make room for next 3 bits
1246
1247 switch (turbulence.type()) {
1248 case SkPerlinNoiseShader::kFractalNoise_Type:
1249 key |= 0x1;
1250 break;
1251 case SkPerlinNoiseShader::kTurbulence_Type:
1252 key |= 0x2;
1253 break;
1254 default:
1255 // leave key at 0
1256 break;
1257 }
1258
1259 if (turbulence.stitchTiles()) {
1260 key |= 0x4; // Flip the 3rd bit if tile stitching is on
1261 }
1262
bsalomon@google.com77af6802013-10-02 13:04:56 +00001263 return key;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001264}
1265
sugoi@google.com4775cba2013-04-17 13:46:56 +00001266void GrGLNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001267 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1268
1269 const SkVector& baseFrequency = turbulence.baseFrequency();
1270 uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001271 uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
1272
1273 SkMatrix m = turbulence.matrix();
bsalomon@google.com77af6802013-10-02 13:04:56 +00001274 m.postTranslate(-SK_Scalar1, -SK_Scalar1);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001275 SkMatrix invM;
1276 if (!m.invert(&invM)) {
1277 invM.reset();
1278 } else {
1279 invM.postConcat(invM); // Square the matrix
1280 }
1281 uman.setSkMatrix(fInvMatrixUni, invM);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001282}
1283
sugoi@google.com4775cba2013-04-17 13:46:56 +00001284void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1285 INHERITED::setData(uman, drawEffect);
1286
1287 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1288 if (turbulence.stitchTiles()) {
1289 const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001290 uman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
1291 SkIntToScalar(stitchData.fHeight));
sugoi@google.com4775cba2013-04-17 13:46:56 +00001292 }
1293}
1294
1295void GrGLSimplexNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1296 INHERITED::setData(uman, drawEffect);
1297
1298 const GrSimplexNoiseEffect& turbulence = drawEffect.castEffect<GrSimplexNoiseEffect>();
1299 uman.set1f(fSeedUni, turbulence.seed());
1300}
1301
sugoi@google.come3b4c502013-04-05 13:47:09 +00001302/////////////////////////////////////////////////////////////////////
1303
1304GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001305 SkASSERT(NULL != context);
1306
commit-bot@chromium.orgc2a0ea62013-11-06 10:08:38 +00001307 if (0 == fNumOctaves) {
1308 SkColor clearColor = 0;
1309 if (kFractalNoise_Type == fType) {
1310 clearColor = SkColorSetARGB(paint.getAlpha() / 2, 127, 127, 127);
1311 }
1312 SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(
1313 clearColor, SkXfermode::kSrc_Mode));
1314 return cf->asNewEffect(context);
1315 }
1316
sugoi@google.come3b4c502013-04-05 13:47:09 +00001317 // Either we don't stitch tiles, either we have a valid tile size
1318 SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
1319
sugoi@google.com4775cba2013-04-17 13:46:56 +00001320#ifdef SK_USE_SIMPLEX_NOISE
1321 // Simplex noise is currently disabled but can be enabled by defining SK_USE_SIMPLEX_NOISE
1322 sk_ignore_unused_variable(context);
1323 GrEffectRef* effect =
1324 GrSimplexNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
1325 fNumOctaves, fStitchTiles, fSeed,
1326 this->getLocalMatrix(), paint.getAlpha());
1327#else
sugoi@google.come3b4c502013-04-05 13:47:09 +00001328 GrTexture* permutationsTexture = GrLockAndRefCachedBitmapTexture(
1329 context, *fPaintingData->getPermutationsBitmap(), NULL);
1330 GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture(
1331 context, *fPaintingData->getNoiseBitmap(), NULL);
1332
1333 GrEffectRef* effect = (NULL != permutationsTexture) && (NULL != noiseTexture) ?
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001334 GrPerlinNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001335 fNumOctaves, fStitchTiles,
1336 fPaintingData->fStitchDataInit,
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001337 permutationsTexture, noiseTexture,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001338 this->getLocalMatrix(), paint.getAlpha()) :
1339 NULL;
1340
1341 // Unlock immediately, this is not great, but we don't have a way of
1342 // knowing when else to unlock it currently. TODO: Remove this when
1343 // unref becomes the unlock replacement for all types of textures.
1344 if (NULL != permutationsTexture) {
1345 GrUnlockAndUnrefCachedBitmapTexture(permutationsTexture);
1346 }
1347 if (NULL != noiseTexture) {
1348 GrUnlockAndUnrefCachedBitmapTexture(noiseTexture);
1349 }
sugoi@google.com4775cba2013-04-17 13:46:56 +00001350#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +00001351
1352 return effect;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001353}
1354
1355#else
1356
1357GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext*, const SkPaint&) const {
1358 SkDEBUGFAIL("Should not call in GPU-less build");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001359 return NULL;
1360}
1361
1362#endif
1363
1364#ifdef SK_DEVELOPER
1365void SkPerlinNoiseShader::toString(SkString* str) const {
1366 str->append("SkPerlinNoiseShader: (");
1367
1368 str->append("type: ");
1369 switch (fType) {
1370 case kFractalNoise_Type:
1371 str->append("\"fractal noise\"");
1372 break;
1373 case kTurbulence_Type:
1374 str->append("\"turbulence\"");
1375 break;
1376 default:
1377 str->append("\"unknown\"");
1378 break;
1379 }
1380 str->append(" base frequency: (");
1381 str->appendScalar(fBaseFrequencyX);
1382 str->append(", ");
1383 str->appendScalar(fBaseFrequencyY);
1384 str->append(") number of octaves: ");
1385 str->appendS32(fNumOctaves);
1386 str->append(" seed: ");
1387 str->appendScalar(fSeed);
1388 str->append(" stitch tiles: ");
1389 str->append(fStitchTiles ? "true " : "false ");
1390
1391 this->INHERITED::toString(str);
1392
1393 str->append(")");
1394}
1395#endif