blob: df6b78e9e156cb4d2828c3288588410f39753ce4 [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"
bsalomon@google.com77af6802013-10-02 13:04:56 +000017#include "GrCoordTransform.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000018#include "gl/GrGLEffect.h"
sugoi@google.come3b4c502013-04-05 13:47:09 +000019#include "GrTBackendEffectFactory.h"
20#include "SkGr.h"
21#endif
22
23static const int kBlockSize = 256;
24static const int kBlockMask = kBlockSize - 1;
25static const int kPerlinNoise = 4096;
26static const int kRandMaximum = SK_MaxS32; // 2**31 - 1
27
28namespace {
29
30// noiseValue is the color component's value (or color)
31// limitValue is the maximum perlin noise array index value allowed
32// newValue is the current noise dimension (either width or height)
33inline int checkNoise(int noiseValue, int limitValue, int newValue) {
34 // If the noise value would bring us out of bounds of the current noise array while we are
35 // stiching noise tiles together, wrap the noise around the current dimension of the noise to
36 // stay within the array bounds in a continuous fashion (so that tiling lines are not visible)
37 if (noiseValue >= limitValue) {
38 noiseValue -= newValue;
39 }
40 if (noiseValue >= limitValue - 1) {
41 noiseValue -= newValue - 1;
42 }
43 return noiseValue;
44}
45
46inline SkScalar smoothCurve(SkScalar t) {
47 static const SkScalar SK_Scalar3 = SkFloatToScalar(3.0f);
48
49 // returns t * t * (3 - 2 * t)
50 return SkScalarMul(SkScalarSquare(t), SK_Scalar3 - 2 * t);
51}
52
53} // end namespace
54
55struct SkPerlinNoiseShader::StitchData {
56 StitchData()
57 : fWidth(0)
58 , fWrapX(0)
59 , fHeight(0)
60 , fWrapY(0)
61 {}
62
63 bool operator==(const StitchData& other) const {
64 return fWidth == other.fWidth &&
65 fWrapX == other.fWrapX &&
66 fHeight == other.fHeight &&
67 fWrapY == other.fWrapY;
68 }
69
70 int fWidth; // How much to subtract to wrap for stitching.
71 int fWrapX; // Minimum value to wrap.
72 int fHeight;
73 int fWrapY;
74};
75
76struct SkPerlinNoiseShader::PaintingData {
77 PaintingData(const SkISize& tileSize)
78 : fSeed(0)
79 , fTileSize(tileSize)
80 , fPermutationsBitmap(NULL)
81 , fNoiseBitmap(NULL)
82 {}
83
84 ~PaintingData()
85 {
86 SkDELETE(fPermutationsBitmap);
87 SkDELETE(fNoiseBitmap);
88 }
89
90 int fSeed;
91 uint8_t fLatticeSelector[kBlockSize];
92 uint16_t fNoise[4][kBlockSize][2];
93 SkPoint fGradient[4][kBlockSize];
94 SkISize fTileSize;
95 SkVector fBaseFrequency;
96 StitchData fStitchDataInit;
97
98private:
99
100 SkBitmap* fPermutationsBitmap;
101 SkBitmap* fNoiseBitmap;
102
103public:
104
105 inline int random() {
106 static const int gRandAmplitude = 16807; // 7**5; primitive root of m
107 static const int gRandQ = 127773; // m / a
108 static const int gRandR = 2836; // m % a
109
110 int result = gRandAmplitude * (fSeed % gRandQ) - gRandR * (fSeed / gRandQ);
111 if (result <= 0)
112 result += kRandMaximum;
113 fSeed = result;
114 return result;
115 }
116
117 void init(SkScalar seed)
118 {
119 static const SkScalar gInvBlockSizef = SkScalarInvert(SkIntToScalar(kBlockSize));
120
121 // The seed value clamp to the range [1, kRandMaximum - 1].
122 fSeed = SkScalarRoundToInt(seed);
123 if (fSeed <= 0) {
124 fSeed = -(fSeed % (kRandMaximum - 1)) + 1;
125 }
126 if (fSeed > kRandMaximum - 1) {
127 fSeed = kRandMaximum - 1;
128 }
129 for (int channel = 0; channel < 4; ++channel) {
130 for (int i = 0; i < kBlockSize; ++i) {
131 fLatticeSelector[i] = i;
132 fNoise[channel][i][0] = (random() % (2 * kBlockSize));
133 fNoise[channel][i][1] = (random() % (2 * kBlockSize));
134 }
135 }
136 for (int i = kBlockSize - 1; i > 0; --i) {
137 int k = fLatticeSelector[i];
138 int j = random() % kBlockSize;
139 SkASSERT(j >= 0);
140 SkASSERT(j < kBlockSize);
141 fLatticeSelector[i] = fLatticeSelector[j];
142 fLatticeSelector[j] = k;
143 }
144
145 // Perform the permutations now
146 {
147 // Copy noise data
148 uint16_t noise[4][kBlockSize][2];
149 for (int i = 0; i < kBlockSize; ++i) {
150 for (int channel = 0; channel < 4; ++channel) {
151 for (int j = 0; j < 2; ++j) {
152 noise[channel][i][j] = fNoise[channel][i][j];
153 }
154 }
155 }
156 // Do permutations on noise data
157 for (int i = 0; i < kBlockSize; ++i) {
158 for (int channel = 0; channel < 4; ++channel) {
159 for (int j = 0; j < 2; ++j) {
160 fNoise[channel][i][j] = noise[channel][fLatticeSelector[i]][j];
161 }
162 }
163 }
164 }
165
166 // Half of the largest possible value for 16 bit unsigned int
sugoi@google.comd537af52013-06-10 13:59:25 +0000167 static const SkScalar gHalfMax16bits = SkFloatToScalar(32767.5f);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000168
169 // Compute gradients from permutated noise data
170 for (int channel = 0; channel < 4; ++channel) {
171 for (int i = 0; i < kBlockSize; ++i) {
172 fGradient[channel][i] = SkPoint::Make(
173 SkScalarMul(SkIntToScalar(fNoise[channel][i][0] - kBlockSize),
174 gInvBlockSizef),
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000175 SkScalarMul(SkIntToScalar(fNoise[channel][i][1] - kBlockSize),
sugoi@google.come3b4c502013-04-05 13:47:09 +0000176 gInvBlockSizef));
177 fGradient[channel][i].normalize();
178 // Put the normalized gradient back into the noise data
179 fNoise[channel][i][0] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000180 fGradient[channel][i].fX + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000181 fNoise[channel][i][1] = SkScalarRoundToInt(SkScalarMul(
sugoi@google.comd537af52013-06-10 13:59:25 +0000182 fGradient[channel][i].fY + SK_Scalar1, gHalfMax16bits));
sugoi@google.come3b4c502013-04-05 13:47:09 +0000183 }
184 }
185
186 // Invalidate bitmaps
187 SkDELETE(fPermutationsBitmap);
188 fPermutationsBitmap = NULL;
189 SkDELETE(fNoiseBitmap);
190 fNoiseBitmap = NULL;
191 }
192
193 void stitch() {
194 SkScalar tileWidth = SkIntToScalar(fTileSize.width());
195 SkScalar tileHeight = SkIntToScalar(fTileSize.height());
196 SkASSERT(tileWidth > 0 && tileHeight > 0);
197 // When stitching tiled turbulence, the frequencies must be adjusted
198 // so that the tile borders will be continuous.
199 if (fBaseFrequency.fX) {
200 SkScalar lowFrequencx = SkScalarDiv(
201 SkScalarMulFloor(tileWidth, fBaseFrequency.fX), tileWidth);
202 SkScalar highFrequencx = SkScalarDiv(
203 SkScalarMulCeil(tileWidth, fBaseFrequency.fX), tileWidth);
204 // BaseFrequency should be non-negative according to the standard.
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000205 if (SkScalarDiv(fBaseFrequency.fX, lowFrequencx) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000206 SkScalarDiv(highFrequencx, fBaseFrequency.fX)) {
207 fBaseFrequency.fX = lowFrequencx;
208 } else {
209 fBaseFrequency.fX = highFrequencx;
210 }
211 }
212 if (fBaseFrequency.fY) {
213 SkScalar lowFrequency = SkScalarDiv(
214 SkScalarMulFloor(tileHeight, fBaseFrequency.fY), tileHeight);
215 SkScalar highFrequency = SkScalarDiv(
216 SkScalarMulCeil(tileHeight, fBaseFrequency.fY), tileHeight);
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000217 if (SkScalarDiv(fBaseFrequency.fY, lowFrequency) <
sugoi@google.come3b4c502013-04-05 13:47:09 +0000218 SkScalarDiv(highFrequency, fBaseFrequency.fY)) {
219 fBaseFrequency.fY = lowFrequency;
220 } else {
221 fBaseFrequency.fY = highFrequency;
222 }
223 }
224 // Set up TurbulenceInitial stitch values.
225 fStitchDataInit.fWidth =
226 SkScalarMulRound(tileWidth, fBaseFrequency.fX);
227 fStitchDataInit.fWrapX = kPerlinNoise + fStitchDataInit.fWidth;
228 fStitchDataInit.fHeight =
229 SkScalarMulRound(tileHeight, fBaseFrequency.fY);
230 fStitchDataInit.fWrapY = kPerlinNoise + fStitchDataInit.fHeight;
231 }
232
233 SkBitmap* getPermutationsBitmap()
234 {
235 if (!fPermutationsBitmap) {
236 fPermutationsBitmap = SkNEW(SkBitmap);
237 fPermutationsBitmap->setConfig(SkBitmap::kA8_Config, kBlockSize, 1);
238 fPermutationsBitmap->allocPixels();
239 uint8_t* bitmapPixels = fPermutationsBitmap->getAddr8(0, 0);
240 memcpy(bitmapPixels, fLatticeSelector, sizeof(uint8_t) * kBlockSize);
241 }
242 return fPermutationsBitmap;
243 }
244
245 SkBitmap* getNoiseBitmap()
246 {
247 if (!fNoiseBitmap) {
248 fNoiseBitmap = SkNEW(SkBitmap);
249 fNoiseBitmap->setConfig(SkBitmap::kARGB_8888_Config, kBlockSize, 4);
250 fNoiseBitmap->allocPixels();
251 uint32_t* bitmapPixels = fNoiseBitmap->getAddr32(0, 0);
252 memcpy(bitmapPixels, fNoise[0][0], sizeof(uint16_t) * kBlockSize * 4 * 2);
253 }
254 return fNoiseBitmap;
255 }
256};
257
258SkShader* SkPerlinNoiseShader::CreateFractalNoise(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
259 int numOctaves, SkScalar seed,
260 const SkISize* tileSize) {
261 return SkNEW_ARGS(SkPerlinNoiseShader, (kFractalNoise_Type, baseFrequencyX, baseFrequencyY,
262 numOctaves, seed, tileSize));
263}
264
265SkShader* SkPerlinNoiseShader::CreateTubulence(SkScalar baseFrequencyX, SkScalar baseFrequencyY,
266 int numOctaves, SkScalar seed,
267 const SkISize* tileSize) {
268 return SkNEW_ARGS(SkPerlinNoiseShader, (kTurbulence_Type, baseFrequencyX, baseFrequencyY,
269 numOctaves, seed, tileSize));
270}
271
272SkPerlinNoiseShader::SkPerlinNoiseShader(SkPerlinNoiseShader::Type type,
273 SkScalar baseFrequencyX,
274 SkScalar baseFrequencyY,
275 int numOctaves,
276 SkScalar seed,
277 const SkISize* tileSize)
278 : fType(type)
279 , fBaseFrequencyX(baseFrequencyX)
280 , fBaseFrequencyY(baseFrequencyY)
281 , fNumOctaves(numOctaves & 0xFF /*[0,255] octaves allowed*/)
282 , fSeed(seed)
283 , fStitchTiles((tileSize != NULL) && !tileSize->isEmpty())
284 , fPaintingData(NULL)
285{
286 SkASSERT(numOctaves >= 0 && numOctaves < 256);
287 setTileSize(fStitchTiles ? *tileSize : SkISize::Make(0,0));
288 fMatrix.reset();
289}
290
291SkPerlinNoiseShader::SkPerlinNoiseShader(SkFlattenableReadBuffer& buffer) :
292 INHERITED(buffer), fPaintingData(NULL) {
293 fType = (SkPerlinNoiseShader::Type) buffer.readInt();
294 fBaseFrequencyX = buffer.readScalar();
295 fBaseFrequencyY = buffer.readScalar();
296 fNumOctaves = buffer.readInt();
297 fSeed = buffer.readScalar();
298 fStitchTiles = buffer.readBool();
299 fTileSize.fWidth = buffer.readInt();
300 fTileSize.fHeight = buffer.readInt();
301 setTileSize(fTileSize);
302 fMatrix.reset();
303}
304
305SkPerlinNoiseShader::~SkPerlinNoiseShader() {
306 // Safety, should have been done in endContext()
307 SkDELETE(fPaintingData);
308}
309
310void SkPerlinNoiseShader::flatten(SkFlattenableWriteBuffer& buffer) const {
311 this->INHERITED::flatten(buffer);
312 buffer.writeInt((int) fType);
313 buffer.writeScalar(fBaseFrequencyX);
314 buffer.writeScalar(fBaseFrequencyY);
315 buffer.writeInt(fNumOctaves);
316 buffer.writeScalar(fSeed);
317 buffer.writeBool(fStitchTiles);
318 buffer.writeInt(fTileSize.fWidth);
319 buffer.writeInt(fTileSize.fHeight);
320}
321
322void SkPerlinNoiseShader::initPaint(PaintingData& paintingData)
323{
324 paintingData.init(fSeed);
325
326 // Set frequencies to original values
327 paintingData.fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
328 // Adjust frequecies based on size if stitching is enabled
329 if (fStitchTiles) {
330 paintingData.stitch();
331 }
332}
333
334void SkPerlinNoiseShader::setTileSize(const SkISize& tileSize) {
335 fTileSize = tileSize;
336
337 if (NULL == fPaintingData) {
338 fPaintingData = SkNEW_ARGS(PaintingData, (fTileSize));
339 initPaint(*fPaintingData);
340 } else {
341 // Set Size
342 fPaintingData->fTileSize = fTileSize;
343 // Set frequencies to original values
344 fPaintingData->fBaseFrequency.set(fBaseFrequencyX, fBaseFrequencyY);
345 // Adjust frequecies based on size if stitching is enabled
346 if (fStitchTiles) {
347 fPaintingData->stitch();
348 }
349 }
350}
351
352SkScalar SkPerlinNoiseShader::noise2D(int channel, const PaintingData& paintingData,
353 const StitchData& stitchData, const SkPoint& noiseVector)
354{
355 struct Noise {
356 int noisePositionIntegerValue;
357 SkScalar noisePositionFractionValue;
358 Noise(SkScalar component)
359 {
360 SkScalar position = component + kPerlinNoise;
361 noisePositionIntegerValue = SkScalarFloorToInt(position);
362 noisePositionFractionValue = position - SkIntToScalar(noisePositionIntegerValue);
363 }
364 };
365 Noise noiseX(noiseVector.x());
366 Noise noiseY(noiseVector.y());
367 SkScalar u, v;
368 // If stitching, adjust lattice points accordingly.
369 if (fStitchTiles) {
370 noiseX.noisePositionIntegerValue =
371 checkNoise(noiseX.noisePositionIntegerValue, stitchData.fWrapX, stitchData.fWidth);
372 noiseY.noisePositionIntegerValue =
373 checkNoise(noiseY.noisePositionIntegerValue, stitchData.fWrapY, stitchData.fHeight);
374 }
375 noiseX.noisePositionIntegerValue &= kBlockMask;
376 noiseY.noisePositionIntegerValue &= kBlockMask;
377 int latticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000378 paintingData.fLatticeSelector[noiseX.noisePositionIntegerValue] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000379 noiseY.noisePositionIntegerValue;
380 int nextLatticeIndex =
skia.committer@gmail.comcff02432013-04-06 07:01:10 +0000381 paintingData.fLatticeSelector[(noiseX.noisePositionIntegerValue + 1) & kBlockMask] +
sugoi@google.come3b4c502013-04-05 13:47:09 +0000382 noiseY.noisePositionIntegerValue;
383 SkScalar sx = smoothCurve(noiseX.noisePositionFractionValue);
384 SkScalar sy = smoothCurve(noiseY.noisePositionFractionValue);
385 // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement
386 SkPoint fractionValue = SkPoint::Make(noiseX.noisePositionFractionValue,
387 noiseY.noisePositionFractionValue); // Offset (0,0)
388 u = paintingData.fGradient[channel][latticeIndex & kBlockMask].dot(fractionValue);
389 fractionValue.fX -= SK_Scalar1; // Offset (-1,0)
390 v = paintingData.fGradient[channel][nextLatticeIndex & kBlockMask].dot(fractionValue);
391 SkScalar a = SkScalarInterp(u, v, sx);
392 fractionValue.fY -= SK_Scalar1; // Offset (-1,-1)
393 v = paintingData.fGradient[channel][(nextLatticeIndex + 1) & kBlockMask].dot(fractionValue);
394 fractionValue.fX = noiseX.noisePositionFractionValue; // Offset (0,-1)
395 u = paintingData.fGradient[channel][(latticeIndex + 1) & kBlockMask].dot(fractionValue);
396 SkScalar b = SkScalarInterp(u, v, sx);
397 return SkScalarInterp(a, b, sy);
398}
399
400SkScalar SkPerlinNoiseShader::calculateTurbulenceValueForPoint(
401 int channel, const PaintingData& paintingData, StitchData& stitchData, const SkPoint& point)
402{
403 if (fStitchTiles) {
404 // Set up TurbulenceInitial stitch values.
405 stitchData = paintingData.fStitchDataInit;
406 }
407 SkScalar turbulenceFunctionResult = 0;
408 SkPoint noiseVector(SkPoint::Make(SkScalarMul(point.x(), paintingData.fBaseFrequency.fX),
409 SkScalarMul(point.y(), paintingData.fBaseFrequency.fY)));
410 SkScalar ratio = SK_Scalar1;
411 for (int octave = 0; octave < fNumOctaves; ++octave) {
412 SkScalar noise = noise2D(channel, paintingData, stitchData, noiseVector);
413 turbulenceFunctionResult += SkScalarDiv(
414 (fType == kFractalNoise_Type) ? noise : SkScalarAbs(noise), ratio);
415 noiseVector.fX *= 2;
416 noiseVector.fY *= 2;
417 ratio *= 2;
418 if (fStitchTiles) {
419 // Update stitch values
420 stitchData.fWidth *= 2;
421 stitchData.fWrapX = stitchData.fWidth + kPerlinNoise;
422 stitchData.fHeight *= 2;
423 stitchData.fWrapY = stitchData.fHeight + kPerlinNoise;
424 }
425 }
426
427 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
428 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
429 if (fType == kFractalNoise_Type) {
430 turbulenceFunctionResult =
431 SkScalarMul(turbulenceFunctionResult, SK_ScalarHalf) + SK_ScalarHalf;
432 }
433
434 if (channel == 3) { // Scale alpha by paint value
435 turbulenceFunctionResult = SkScalarMul(turbulenceFunctionResult,
436 SkScalarDiv(SkIntToScalar(getPaintAlpha()), SkIntToScalar(255)));
437 }
438
439 // Clamp result
440 return SkScalarPin(turbulenceFunctionResult, 0, SK_Scalar1);
441}
442
443SkPMColor SkPerlinNoiseShader::shade(const SkPoint& point, StitchData& stitchData) {
444 SkMatrix matrix = fMatrix;
445 SkMatrix invMatrix;
446 if (!matrix.invert(&invMatrix)) {
447 invMatrix.reset();
448 } else {
449 invMatrix.postConcat(invMatrix); // Square the matrix
450 }
451 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
452 // (as opposed to 0 based, usually). The same adjustment is in the setData() function.
453 matrix.postTranslate(SK_Scalar1, SK_Scalar1);
454 SkPoint newPoint;
455 matrix.mapPoints(&newPoint, &point, 1);
456 invMatrix.mapPoints(&newPoint, &newPoint, 1);
457 newPoint.fX = SkScalarRoundToScalar(newPoint.fX);
458 newPoint.fY = SkScalarRoundToScalar(newPoint.fY);
459
460 U8CPU rgba[4];
461 for (int channel = 3; channel >= 0; --channel) {
462 rgba[channel] = SkScalarFloorToInt(255 *
463 calculateTurbulenceValueForPoint(channel, *fPaintingData, stitchData, newPoint));
464 }
465 return SkPreMultiplyARGB(rgba[3], rgba[0], rgba[1], rgba[2]);
466}
467
468bool SkPerlinNoiseShader::setContext(const SkBitmap& device, const SkPaint& paint,
469 const SkMatrix& matrix) {
470 fMatrix = matrix;
471 return INHERITED::setContext(device, paint, matrix);
472}
473
474void SkPerlinNoiseShader::shadeSpan(int x, int y, SkPMColor result[], int count) {
475 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
476 StitchData stitchData;
477 for (int i = 0; i < count; ++i) {
478 result[i] = shade(point, stitchData);
479 point.fX += SK_Scalar1;
480 }
481}
482
483void SkPerlinNoiseShader::shadeSpan16(int x, int y, uint16_t result[], int count) {
484 SkPoint point = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y));
485 StitchData stitchData;
486 DITHER_565_SCAN(y);
487 for (int i = 0; i < count; ++i) {
488 unsigned dither = DITHER_VALUE(x);
489 result[i] = SkDitherRGB32To565(shade(point, stitchData), dither);
490 DITHER_INC_X(x);
491 point.fX += SK_Scalar1;
492 }
493}
494
495/////////////////////////////////////////////////////////////////////
496
commit-bot@chromium.org344cf452013-06-17 14:19:01 +0000497#if SK_SUPPORT_GPU
sugoi@google.come3b4c502013-04-05 13:47:09 +0000498
499#include "GrTBackendEffectFactory.h"
500
sugoi@google.com4775cba2013-04-17 13:46:56 +0000501class GrGLNoise : public GrGLEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000502public:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000503 GrGLNoise(const GrBackendEffectFactory& factory,
504 const GrDrawEffect& drawEffect);
505 virtual ~GrGLNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000506
sugoi@google.com4775cba2013-04-17 13:46:56 +0000507 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
508
509 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
510
511protected:
512 SkPerlinNoiseShader::Type fType;
513 bool fStitchTiles;
514 int fNumOctaves;
515 GrGLUniformManager::UniformHandle fBaseFrequencyUni;
516 GrGLUniformManager::UniformHandle fAlphaUni;
517 GrGLUniformManager::UniformHandle fInvMatrixUni;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000518
519private:
520 typedef GrGLEffect INHERITED;
521};
522
523class GrGLPerlinNoise : public GrGLNoise {
524public:
sugoi@google.come3b4c502013-04-05 13:47:09 +0000525 GrGLPerlinNoise(const GrBackendEffectFactory& factory,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000526 const GrDrawEffect& drawEffect)
527 : GrGLNoise(factory, drawEffect) {}
528 virtual ~GrGLPerlinNoise() {}
sugoi@google.come3b4c502013-04-05 13:47:09 +0000529
530 virtual void emitCode(GrGLShaderBuilder*,
531 const GrDrawEffect&,
532 EffectKey,
533 const char* outputColor,
534 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000535 const TransformedCoordsArray&,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000536 const TextureSamplerArray&) SK_OVERRIDE;
537
sugoi@google.com4775cba2013-04-17 13:46:56 +0000538 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000539
540private:
sugoi@google.com4775cba2013-04-17 13:46:56 +0000541 GrGLUniformManager::UniformHandle fStitchDataUni;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000542
sugoi@google.com4775cba2013-04-17 13:46:56 +0000543 typedef GrGLNoise INHERITED;
544};
545
546class GrGLSimplexNoise : public GrGLNoise {
547 // Note : This is for reference only. GrGLPerlinNoise is used for processing.
548public:
549 GrGLSimplexNoise(const GrBackendEffectFactory& factory,
550 const GrDrawEffect& drawEffect)
551 : GrGLNoise(factory, drawEffect) {}
552
553 virtual ~GrGLSimplexNoise() {}
554
555 virtual void emitCode(GrGLShaderBuilder*,
556 const GrDrawEffect&,
557 EffectKey,
558 const char* outputColor,
559 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000560 const TransformedCoordsArray&,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000561 const TextureSamplerArray&) SK_OVERRIDE;
562
563 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
564
565private:
566 GrGLUniformManager::UniformHandle fSeedUni;
567
568 typedef GrGLNoise INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000569};
570
571/////////////////////////////////////////////////////////////////////
572
sugoi@google.com4775cba2013-04-17 13:46:56 +0000573class GrNoiseEffect : public GrEffect {
574public:
575 virtual ~GrNoiseEffect() { }
576
577 SkPerlinNoiseShader::Type type() const { return fType; }
578 bool stitchTiles() const { return fStitchTiles; }
579 const SkVector& baseFrequency() const { return fBaseFrequency; }
580 int numOctaves() const { return fNumOctaves; }
bsalomon@google.com77af6802013-10-02 13:04:56 +0000581 const SkMatrix& matrix() const { return fCoordTransform.getMatrix(); }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000582 uint8_t alpha() const { return fAlpha; }
sugoi@google.com4775cba2013-04-17 13:46:56 +0000583
584 void getConstantColorComponents(GrColor*, uint32_t* validFlags) const SK_OVERRIDE {
585 *validFlags = 0; // This is noise. Nothing is constant.
586 }
587
588protected:
589 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
590 const GrNoiseEffect& s = CastEffect<GrNoiseEffect>(sBase);
591 return fType == s.fType &&
592 fBaseFrequency == s.fBaseFrequency &&
593 fNumOctaves == s.fNumOctaves &&
594 fStitchTiles == s.fStitchTiles &&
bsalomon@google.com77af6802013-10-02 13:04:56 +0000595 fCoordTransform.getMatrix() == s.fCoordTransform.getMatrix() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000596 fAlpha == s.fAlpha;
597 }
598
599 GrNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency, int numOctaves,
600 bool stitchTiles, const SkMatrix& matrix, uint8_t alpha)
601 : fType(type)
602 , fBaseFrequency(baseFrequency)
603 , fNumOctaves(numOctaves)
604 , fStitchTiles(stitchTiles)
605 , fMatrix(matrix)
606 , fAlpha(alpha) {
bsalomon@google.com77af6802013-10-02 13:04:56 +0000607 // This (1,1) translation is due to WebKit's 1 based coordinates for the noise
608 // (as opposed to 0 based, usually). The same adjustment is in the shadeSpan() functions.
609 SkMatrix m = matrix;
610 m.postTranslate(SK_Scalar1, SK_Scalar1);
611 fCoordTransform.reset(kLocal_GrCoordSet, m);
612 this->addCoordTransform(&fCoordTransform);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000613 }
614
615 SkPerlinNoiseShader::Type fType;
bsalomon@google.com77af6802013-10-02 13:04:56 +0000616 GrCoordTransform fCoordTransform;
sugoi@google.com4775cba2013-04-17 13:46:56 +0000617 SkVector fBaseFrequency;
618 int fNumOctaves;
619 bool fStitchTiles;
620 SkMatrix fMatrix;
621 uint8_t fAlpha;
622
623private:
624 typedef GrEffect INHERITED;
625};
626
627class GrPerlinNoiseEffect : public GrNoiseEffect {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000628public:
629 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
630 int numOctaves, bool stitchTiles,
631 const SkPerlinNoiseShader::StitchData& stitchData,
632 GrTexture* permutationsTexture, GrTexture* noiseTexture,
633 const SkMatrix& matrix, uint8_t alpha) {
634 AutoEffectUnref effect(SkNEW_ARGS(GrPerlinNoiseEffect, (type, baseFrequency, numOctaves,
635 stitchTiles, stitchData, permutationsTexture, noiseTexture, matrix, alpha)));
636 return CreateEffectRef(effect);
637 }
638
639 virtual ~GrPerlinNoiseEffect() { }
640
641 static const char* Name() { return "PerlinNoise"; }
642 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
643 return GrTBackendEffectFactory<GrPerlinNoiseEffect>::getInstance();
644 }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000645 const SkPerlinNoiseShader::StitchData& stitchData() const { return fStitchData; }
sugoi@google.come3b4c502013-04-05 13:47:09 +0000646
647 typedef GrGLPerlinNoise GLEffect;
648
sugoi@google.come3b4c502013-04-05 13:47:09 +0000649private:
650 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
651 const GrPerlinNoiseEffect& s = CastEffect<GrPerlinNoiseEffect>(sBase);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000652 return INHERITED::onIsEqual(sBase) &&
653 fPermutationsAccess.getTexture() == s.fPermutationsAccess.getTexture() &&
sugoi@google.come3b4c502013-04-05 13:47:09 +0000654 fNoiseAccess.getTexture() == s.fNoiseAccess.getTexture() &&
sugoi@google.com4775cba2013-04-17 13:46:56 +0000655 fStitchData == s.fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000656 }
657
658 GrPerlinNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
659 int numOctaves, bool stitchTiles,
660 const SkPerlinNoiseShader::StitchData& stitchData,
661 GrTexture* permutationsTexture, GrTexture* noiseTexture,
662 const SkMatrix& matrix, uint8_t alpha)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000663 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
664 , fPermutationsAccess(permutationsTexture)
sugoi@google.come3b4c502013-04-05 13:47:09 +0000665 , fNoiseAccess(noiseTexture)
sugoi@google.com4775cba2013-04-17 13:46:56 +0000666 , fStitchData(stitchData) {
sugoi@google.come3b4c502013-04-05 13:47:09 +0000667 this->addTextureAccess(&fPermutationsAccess);
668 this->addTextureAccess(&fNoiseAccess);
669 }
670
sugoi@google.com4775cba2013-04-17 13:46:56 +0000671 GR_DECLARE_EFFECT_TEST;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000672
673 GrTextureAccess fPermutationsAccess;
674 GrTextureAccess fNoiseAccess;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000675 SkPerlinNoiseShader::StitchData fStitchData;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000676
sugoi@google.com4775cba2013-04-17 13:46:56 +0000677 typedef GrNoiseEffect INHERITED;
678};
679
680class GrSimplexNoiseEffect : public GrNoiseEffect {
681 // Note : This is for reference only. GrPerlinNoiseEffect is used for processing.
682public:
683 static GrEffectRef* Create(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
684 int numOctaves, bool stitchTiles, const SkScalar seed,
685 const SkMatrix& matrix, uint8_t alpha) {
686 AutoEffectUnref effect(SkNEW_ARGS(GrSimplexNoiseEffect, (type, baseFrequency, numOctaves,
687 stitchTiles, seed, matrix, alpha)));
688 return CreateEffectRef(effect);
689 }
690
691 virtual ~GrSimplexNoiseEffect() { }
692
693 static const char* Name() { return "SimplexNoise"; }
694 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
695 return GrTBackendEffectFactory<GrSimplexNoiseEffect>::getInstance();
696 }
697 const SkScalar& seed() const { return fSeed; }
698
699 typedef GrGLSimplexNoise GLEffect;
700
701private:
702 virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE {
703 const GrSimplexNoiseEffect& s = CastEffect<GrSimplexNoiseEffect>(sBase);
704 return INHERITED::onIsEqual(sBase) && fSeed == s.fSeed;
705 }
706
707 GrSimplexNoiseEffect(SkPerlinNoiseShader::Type type, const SkVector& baseFrequency,
708 int numOctaves, bool stitchTiles, const SkScalar seed,
709 const SkMatrix& matrix, uint8_t alpha)
710 : GrNoiseEffect(type, baseFrequency, numOctaves, stitchTiles, matrix, alpha)
711 , fSeed(seed) {
712 }
713
714 SkScalar fSeed;
715
716 typedef GrNoiseEffect INHERITED;
sugoi@google.come3b4c502013-04-05 13:47:09 +0000717};
718
719/////////////////////////////////////////////////////////////////////
sugoi@google.come3b4c502013-04-05 13:47:09 +0000720GR_DEFINE_EFFECT_TEST(GrPerlinNoiseEffect);
721
commit-bot@chromium.orge0e7cfe2013-09-09 20:09:12 +0000722GrEffectRef* GrPerlinNoiseEffect::TestCreate(SkRandom* random,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000723 GrContext* context,
724 const GrDrawTargetCaps&,
725 GrTexture**) {
sugoi@google.com423ac132013-04-18 14:04:57 +0000726 int numOctaves = random->nextRangeU(2, 10);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000727 bool stitchTiles = random->nextBool();
728 SkScalar seed = SkIntToScalar(random->nextU());
729 SkISize tileSize = SkISize::Make(random->nextRangeU(4, 4096), random->nextRangeU(4, 4096));
730 SkScalar baseFrequencyX = random->nextRangeScalar(SkFloatToScalar(0.01f),
731 SkFloatToScalar(0.99f));
732 SkScalar baseFrequencyY = random->nextRangeScalar(SkFloatToScalar(0.01f),
733 SkFloatToScalar(0.99f));
734
735 SkShader* shader = random->nextBool() ?
736 SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed,
737 stitchTiles ? &tileSize : NULL) :
738 SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed,
739 stitchTiles ? &tileSize : NULL);
740
741 SkPaint paint;
742 GrEffectRef* effect = shader->asNewEffect(context, paint);
743
744 SkDELETE(shader);
745
746 return effect;
747}
sugoi@google.com4775cba2013-04-17 13:46:56 +0000748
sugoi@google.come3b4c502013-04-05 13:47:09 +0000749/////////////////////////////////////////////////////////////////////
750
sugoi@google.com4775cba2013-04-17 13:46:56 +0000751void GrGLSimplexNoise::emitCode(GrGLShaderBuilder* builder,
752 const GrDrawEffect&,
753 EffectKey key,
754 const char* outputColor,
755 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000756 const TransformedCoordsArray& coords,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000757 const TextureSamplerArray&) {
758 sk_ignore_unused_variable(inputColor);
759
bsalomon@google.com77af6802013-10-02 13:04:56 +0000760 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000761
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000762 fSeedUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000763 kFloat_GrSLType, "seed");
764 const char* seedUni = builder->getUniformCStr(fSeedUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000765 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000766 kMat33f_GrSLType, "invMatrix");
767 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000768 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000769 kVec2f_GrSLType, "baseFrequency");
770 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000771 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000772 kFloat_GrSLType, "alpha");
773 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
774
775 // Add vec3 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000776 static const GrGLShaderVar gVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000777 GrGLShaderVar("x", kVec3f_GrSLType)
778 };
779
780 SkString mod289_3_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000781 builder->fsEmitFunction(kVec3f_GrSLType,
782 "mod289", SK_ARRAY_COUNT(gVec3Args), gVec3Args,
783 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
784 "return x - floor(x * C.xxx) * C.yyy;", &mod289_3_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000785
786 // Add vec4 modulo 289 function
sugoi@google.comd537af52013-06-10 13:59:25 +0000787 static const GrGLShaderVar gVec4Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000788 GrGLShaderVar("x", kVec4f_GrSLType)
789 };
790
791 SkString mod289_4_funcName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000792 builder->fsEmitFunction(kVec4f_GrSLType,
793 "mod289", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
794 "const vec2 C = vec2(1.0 / 289.0, 289.0);\n"
795 "return x - floor(x * C.xxxx) * C.yyyy;", &mod289_4_funcName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000796
797 // Add vec4 permute function
sugoi@google.comd537af52013-06-10 13:59:25 +0000798 SkString permuteCode;
799 permuteCode.appendf("const vec2 C = vec2(34.0, 1.0);\n"
800 "return %s(((x * C.xxxx) + C.yyyy) * x);", mod289_4_funcName.c_str());
801 SkString permuteFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000802 builder->fsEmitFunction(kVec4f_GrSLType,
803 "permute", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
804 permuteCode.c_str(), &permuteFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000805
806 // Add vec4 taylorInvSqrt function
sugoi@google.comd537af52013-06-10 13:59:25 +0000807 SkString taylorInvSqrtFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000808 builder->fsEmitFunction(kVec4f_GrSLType,
809 "taylorInvSqrt", SK_ARRAY_COUNT(gVec4Args), gVec4Args,
810 "const vec2 C = vec2(-0.85373472095314, 1.79284291400159);\n"
811 "return x * C.xxxx + C.yyyy;", &taylorInvSqrtFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000812
813 // Add vec3 noise function
sugoi@google.comd537af52013-06-10 13:59:25 +0000814 static const GrGLShaderVar gNoiseVec3Args[] = {
sugoi@google.com4775cba2013-04-17 13:46:56 +0000815 GrGLShaderVar("v", kVec3f_GrSLType)
816 };
817
sugoi@google.comd537af52013-06-10 13:59:25 +0000818 SkString noiseCode;
819 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000820 "const vec2 C = vec2(1.0/6.0, 1.0/3.0);\n"
821 "const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n"
822
823 // First corner
824 "vec3 i = floor(v + dot(v, C.yyy));\n"
825 "vec3 x0 = v - i + dot(i, C.xxx);\n"
826
827 // Other corners
828 "vec3 g = step(x0.yzx, x0.xyz);\n"
829 "vec3 l = 1.0 - g;\n"
830 "vec3 i1 = min(g.xyz, l.zxy);\n"
831 "vec3 i2 = max(g.xyz, l.zxy);\n"
832
833 "vec3 x1 = x0 - i1 + C.xxx;\n"
834 "vec3 x2 = x0 - i2 + C.yyy;\n" // 2.0*C.x = 1/3 = C.y
835 "vec3 x3 = x0 - D.yyy;\n" // -1.0+3.0*C.x = -0.5 = -D.y
836 );
837
sugoi@google.comd537af52013-06-10 13:59:25 +0000838 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000839 // Permutations
840 "i = %s(i);\n"
841 "vec4 p = %s(%s(%s(\n"
842 " i.z + vec4(0.0, i1.z, i2.z, 1.0)) +\n"
843 " i.y + vec4(0.0, i1.y, i2.y, 1.0)) +\n"
844 " i.x + vec4(0.0, i1.x, i2.x, 1.0));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000845 mod289_3_funcName.c_str(), permuteFuncName.c_str(), permuteFuncName.c_str(),
846 permuteFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000847
sugoi@google.comd537af52013-06-10 13:59:25 +0000848 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000849 // Gradients: 7x7 points over a square, mapped onto an octahedron.
850 // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
851 "float n_ = 0.142857142857;\n" // 1.0/7.0
852 "vec3 ns = n_ * D.wyz - D.xzx;\n"
853
854 "vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\n" // mod(p,7*7)
855
856 "vec4 x_ = floor(j * ns.z);\n"
857 "vec4 y_ = floor(j - 7.0 * x_);" // mod(j,N)
858
859 "vec4 x = x_ *ns.x + ns.yyyy;\n"
860 "vec4 y = y_ *ns.x + ns.yyyy;\n"
861 "vec4 h = 1.0 - abs(x) - abs(y);\n"
862
863 "vec4 b0 = vec4(x.xy, y.xy);\n"
864 "vec4 b1 = vec4(x.zw, y.zw);\n"
865 );
866
sugoi@google.comd537af52013-06-10 13:59:25 +0000867 noiseCode.append(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000868 "vec4 s0 = floor(b0) * 2.0 + 1.0;\n"
869 "vec4 s1 = floor(b1) * 2.0 + 1.0;\n"
870 "vec4 sh = -step(h, vec4(0.0));\n"
871
872 "vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;\n"
873 "vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;\n"
874
875 "vec3 p0 = vec3(a0.xy, h.x);\n"
876 "vec3 p1 = vec3(a0.zw, h.y);\n"
877 "vec3 p2 = vec3(a1.xy, h.z);\n"
878 "vec3 p3 = vec3(a1.zw, h.w);\n"
879 );
880
sugoi@google.comd537af52013-06-10 13:59:25 +0000881 noiseCode.appendf(
sugoi@google.com4775cba2013-04-17 13:46:56 +0000882 // Normalise gradients
883 "vec4 norm = %s(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n"
884 "p0 *= norm.x;\n"
885 "p1 *= norm.y;\n"
886 "p2 *= norm.z;\n"
887 "p3 *= norm.w;\n"
888
889 // Mix final noise value
890 "vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n"
891 "m = m * m;\n"
892 "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 +0000893 taylorInvSqrtFuncName.c_str());
sugoi@google.com4775cba2013-04-17 13:46:56 +0000894
sugoi@google.comd537af52013-06-10 13:59:25 +0000895 SkString noiseFuncName;
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000896 builder->fsEmitFunction(kFloat_GrSLType,
897 "snoise", SK_ARRAY_COUNT(gNoiseVec3Args), gNoiseVec3Args,
898 noiseCode.c_str(), &noiseFuncName);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000899
900 const char* noiseVecIni = "noiseVecIni";
901 const char* factors = "factors";
902 const char* sum = "sum";
903 const char* xOffsets = "xOffsets";
904 const char* yOffsets = "yOffsets";
905 const char* channel = "channel";
906
907 // Fill with some prime numbers
908 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(13.0, 53.0, 101.0, 151.0);\n", xOffsets);
909 builder->fsCodeAppendf("\t\tconst vec4 %s = vec4(109.0, 167.0, 23.0, 67.0);\n", yOffsets);
910
911 // There are rounding errors if the floor operation is not performed here
912 builder->fsCodeAppendf(
913 "\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 +0000914 noiseVecIni, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000915
916 // Perturb the texcoords with three components of noise
917 builder->fsCodeAppendf("\t\t%s += 0.1 * vec3(%s(%s + vec3( 0.0, 0.0, %s)),"
918 "%s(%s + vec3( 43.0, 17.0, %s)),"
919 "%s(%s + vec3(-17.0, -43.0, %s)));\n",
sugoi@google.comd537af52013-06-10 13:59:25 +0000920 noiseVecIni, noiseFuncName.c_str(), noiseVecIni, seedUni,
921 noiseFuncName.c_str(), noiseVecIni, seedUni,
922 noiseFuncName.c_str(), noiseVecIni, seedUni);
sugoi@google.com4775cba2013-04-17 13:46:56 +0000923
924 builder->fsCodeAppendf("\t\t%s = vec4(0.0);\n", outputColor);
925
926 builder->fsCodeAppendf("\t\tvec3 %s = vec3(1.0);\n", factors);
927 builder->fsCodeAppendf("\t\tfloat %s = 0.0;\n", sum);
928
929 // Loop over all octaves
930 builder->fsCodeAppendf("\t\tfor (int octave = 0; octave < %d; ++octave) {\n", fNumOctaves);
931
932 // Loop over the 4 channels
933 builder->fsCodeAppendf("\t\t\tfor (int %s = 3; %s >= 0; --%s) {\n", channel, channel, channel);
934
935 builder->fsCodeAppendf(
936 "\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 +0000937 outputColor, factors, noiseFuncName.c_str(), noiseVecIni, factors, xOffsets, channel,
sugoi@google.com4775cba2013-04-17 13:46:56 +0000938 yOffsets, channel, seedUni, factors);
939
940 builder->fsCodeAppend("\t\t\t}\n"); // end of the for loop on channels
941
942 builder->fsCodeAppendf("\t\t\t%s += %s.x;\n", sum, factors);
943 builder->fsCodeAppendf("\t\t\t%s *= vec3(0.5, 2.0, 0.75);\n", factors);
944
945 builder->fsCodeAppend("\t\t}\n"); // end of the for loop on octaves
946
947 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
948 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
949 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
950 builder->fsCodeAppendf("\t\t%s = %s * vec4(0.5 / %s) + vec4(0.5);\n",
951 outputColor, outputColor, sum);
952 } else {
953 builder->fsCodeAppendf("\t\t%s = abs(%s / vec4(%s));\n",
954 outputColor, outputColor, sum);
955 }
956
957 builder->fsCodeAppendf("\t\t%s.a *= %s;\n", outputColor, alphaUni);
958
959 // Clamp values
960 builder->fsCodeAppendf("\t\t%s = clamp(%s, 0.0, 1.0);\n", outputColor, outputColor);
961
962 // Pre-multiply the result
963 builder->fsCodeAppendf("\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
964 outputColor, outputColor, outputColor, outputColor);
965}
966
sugoi@google.come3b4c502013-04-05 13:47:09 +0000967void GrGLPerlinNoise::emitCode(GrGLShaderBuilder* builder,
968 const GrDrawEffect&,
969 EffectKey key,
970 const char* outputColor,
971 const char* inputColor,
bsalomon@google.com77af6802013-10-02 13:04:56 +0000972 const TransformedCoordsArray& coords,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000973 const TextureSamplerArray& samplers) {
974 sk_ignore_unused_variable(inputColor);
975
bsalomon@google.com77af6802013-10-02 13:04:56 +0000976 SkString vCoords = builder->ensureFSCoords2D(coords, 0);
sugoi@google.come3b4c502013-04-05 13:47:09 +0000977
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000978 fInvMatrixUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000979 kMat33f_GrSLType, "invMatrix");
980 const char* invMatrixUni = builder->getUniformCStr(fInvMatrixUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000981 fBaseFrequencyUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000982 kVec2f_GrSLType, "baseFrequency");
983 const char* baseFrequencyUni = builder->getUniformCStr(fBaseFrequencyUni);
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000984 fAlphaUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
sugoi@google.come3b4c502013-04-05 13:47:09 +0000985 kFloat_GrSLType, "alpha");
986 const char* alphaUni = builder->getUniformCStr(fAlphaUni);
987
988 const char* stitchDataUni = NULL;
989 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +0000990 fStitchDataUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
commit-bot@chromium.org98393202013-07-04 18:13:05 +0000991 kVec2f_GrSLType, "stitchData");
sugoi@google.come3b4c502013-04-05 13:47:09 +0000992 stitchDataUni = builder->getUniformCStr(fStitchDataUni);
993 }
994
sugoi@google.comd537af52013-06-10 13:59:25 +0000995 // There are 4 lines, so the center of each line is 1/8, 3/8, 5/8 and 7/8
996 const char* chanCoordR = "0.125";
997 const char* chanCoordG = "0.375";
998 const char* chanCoordB = "0.625";
999 const char* chanCoordA = "0.875";
1000 const char* chanCoord = "chanCoord";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001001 const char* stitchData = "stitchData";
1002 const char* ratio = "ratio";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001003 const char* noiseXY = "noiseXY";
1004 const char* noiseVec = "noiseVec";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001005 const char* noiseSmooth = "noiseSmooth";
1006 const char* fractVal = "fractVal";
1007 const char* uv = "uv";
1008 const char* ab = "ab";
1009 const char* latticeIdx = "latticeIdx";
1010 const char* lattice = "lattice";
sugoi@google.come3b4c502013-04-05 13:47:09 +00001011 const char* inc8bit = "0.00390625"; // 1.0 / 256.0
1012 // This is the math to convert the two 16bit integer packed into rgba 8 bit input into a
1013 // [-1,1] vector and perform a dot product between that vector and the provided vector.
1014 const char* dotLattice = "dot(((%s.ga + %s.rb * vec2(%s)) * vec2(2.0) - vec2(1.0)), %s);";
1015
sugoi@google.comd537af52013-06-10 13:59:25 +00001016 // Add noise function
1017 static const GrGLShaderVar gPerlinNoiseArgs[] = {
1018 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001019 GrGLShaderVar(noiseVec, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001020 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001021
sugoi@google.comd537af52013-06-10 13:59:25 +00001022 static const GrGLShaderVar gPerlinNoiseStitchArgs[] = {
1023 GrGLShaderVar(chanCoord, kFloat_GrSLType),
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001024 GrGLShaderVar(noiseVec, kVec2f_GrSLType),
1025 GrGLShaderVar(stitchData, kVec2f_GrSLType)
sugoi@google.comd537af52013-06-10 13:59:25 +00001026 };
sugoi@google.come3b4c502013-04-05 13:47:09 +00001027
sugoi@google.comd537af52013-06-10 13:59:25 +00001028 SkString noiseCode;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001029
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001030 noiseCode.appendf("\tvec4 %s = vec4(floor(%s), fract(%s));", noiseXY, noiseVec, noiseVec);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001031
1032 // smooth curve : t * t * (3 - 2 * t)
sugoi@google.comd537af52013-06-10 13:59:25 +00001033 noiseCode.appendf("\n\tvec2 %s = %s.zw * %s.zw * (vec2(3.0) - vec2(2.0) * %s.zw);",
1034 noiseSmooth, noiseXY, noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001035
1036 // Adjust frequencies if we're stitching tiles
1037 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001038 noiseCode.appendf("\n\tif(%s.x >= %s.x) { %s.x -= %s.x; }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001039 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001040 noiseCode.appendf("\n\tif(%s.x >= (%s.x - 1.0)) { %s.x -= (%s.x - 1.0); }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001041 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001042 noiseCode.appendf("\n\tif(%s.y >= %s.y) { %s.y -= %s.y; }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001043 noiseXY, stitchData, noiseXY, stitchData);
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001044 noiseCode.appendf("\n\tif(%s.y >= (%s.y - 1.0)) { %s.y -= (%s.y - 1.0); }",
sugoi@google.comd537af52013-06-10 13:59:25 +00001045 noiseXY, stitchData, noiseXY, stitchData);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001046 }
1047
1048 // Get texture coordinates and normalize
sugoi@google.comd537af52013-06-10 13:59:25 +00001049 noiseCode.appendf("\n\t%s.xy = fract(floor(mod(%s.xy, 256.0)) / vec2(256.0));\n",
1050 noiseXY, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001051
1052 // Get permutation for x
1053 {
1054 SkString xCoords("");
1055 xCoords.appendf("vec2(%s.x, 0.5)", noiseXY);
1056
sugoi@google.comd537af52013-06-10 13:59:25 +00001057 noiseCode.appendf("\n\tvec2 %s;\n\t%s.x = ", latticeIdx, latticeIdx);
1058 builder->appendTextureLookup(&noiseCode, samplers[0], xCoords.c_str(), kVec2f_GrSLType);
1059 noiseCode.append(".r;");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001060 }
1061
1062 // Get permutation for x + 1
1063 {
1064 SkString xCoords("");
1065 xCoords.appendf("vec2(fract(%s.x + %s), 0.5)", noiseXY, inc8bit);
1066
sugoi@google.comd537af52013-06-10 13:59:25 +00001067 noiseCode.appendf("\n\t%s.y = ", 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
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001072#if defined(SK_BUILD_FOR_ANDROID)
1073 // Android rounding for Tegra devices, like, for example: Xoom (Tegra 2), Nexus 7 (Tegra 3).
1074 // The issue is that colors aren't accurate enough on Tegra devices. For example, if an 8 bit
1075 // value of 124 (or 0.486275 here) is entered, we can get a texture value of 123.513725
1076 // (or 0.484368 here). The following rounding operation prevents these precision issues from
1077 // affecting the result of the noise by making sure that we only have multiples of 1/255.
1078 // (Note that 1/255 is about 0.003921569, which is the value used here).
1079 noiseCode.appendf("\n\t%s = floor(%s * vec2(255.0) + vec2(0.5)) * vec2(0.003921569);",
1080 latticeIdx, latticeIdx);
1081#endif
1082
sugoi@google.come3b4c502013-04-05 13:47:09 +00001083 // Get (x,y) coordinates with the permutated x
sugoi@google.comd537af52013-06-10 13:59:25 +00001084 noiseCode.appendf("\n\t%s = fract(%s + %s.yy);", latticeIdx, latticeIdx, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001085
sugoi@google.comd537af52013-06-10 13:59:25 +00001086 noiseCode.appendf("\n\tvec2 %s = %s.zw;", fractVal, noiseXY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001087
sugoi@google.comd537af52013-06-10 13:59:25 +00001088 noiseCode.appendf("\n\n\tvec2 %s;", uv);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001089 // Compute u, at offset (0,0)
1090 {
1091 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001092 latticeCoords.appendf("vec2(%s.x, %s)", latticeIdx, chanCoord);
1093 noiseCode.appendf("\n\tvec4 %s = ", lattice);
1094 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1095 kVec2f_GrSLType);
1096 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1097 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001098 }
1099
sugoi@google.comd537af52013-06-10 13:59:25 +00001100 noiseCode.appendf("\n\t%s.x -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001101 // Compute v, at offset (-1,0)
1102 {
1103 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001104 latticeCoords.appendf("vec2(%s.y, %s)", latticeIdx, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001105 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001106 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1107 kVec2f_GrSLType);
1108 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1109 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001110 }
1111
1112 // Compute 'a' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001113 noiseCode.appendf("\n\tvec2 %s;", ab);
1114 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 +00001115
sugoi@google.comd537af52013-06-10 13:59:25 +00001116 noiseCode.appendf("\n\t%s.y -= 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001117 // Compute v, at offset (-1,-1)
1118 {
1119 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001120 latticeCoords.appendf("vec2(fract(%s.y + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001121 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001122 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1123 kVec2f_GrSLType);
1124 noiseCode.appendf(".bgra;\n\t%s.y = ", uv);
1125 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001126 }
1127
sugoi@google.comd537af52013-06-10 13:59:25 +00001128 noiseCode.appendf("\n\t%s.x += 1.0;", fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001129 // Compute u, at offset (0,-1)
1130 {
1131 SkString latticeCoords("");
sugoi@google.comd537af52013-06-10 13:59:25 +00001132 latticeCoords.appendf("vec2(fract(%s.x + %s), %s)", latticeIdx, inc8bit, chanCoord);
commit-bot@chromium.org344cf452013-06-17 14:19:01 +00001133 noiseCode.append("\n\tlattice = ");
sugoi@google.comd537af52013-06-10 13:59:25 +00001134 builder->appendTextureLookup(&noiseCode, samplers[1], latticeCoords.c_str(),
1135 kVec2f_GrSLType);
1136 noiseCode.appendf(".bgra;\n\t%s.x = ", uv);
1137 noiseCode.appendf(dotLattice, lattice, lattice, inc8bit, fractVal);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001138 }
1139
1140 // Compute 'b' as a linear interpolation of 'u' and 'v'
sugoi@google.comd537af52013-06-10 13:59:25 +00001141 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 +00001142 // Compute the noise as a linear interpolation of 'a' and 'b'
sugoi@google.comd537af52013-06-10 13:59:25 +00001143 noiseCode.appendf("\n\treturn mix(%s.x, %s.y, %s.y);\n", ab, ab, noiseSmooth);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001144
sugoi@google.comd537af52013-06-10 13:59:25 +00001145 SkString noiseFuncName;
1146 if (fStitchTiles) {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001147 builder->fsEmitFunction(kFloat_GrSLType,
1148 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseStitchArgs),
1149 gPerlinNoiseStitchArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001150 } else {
commit-bot@chromium.org74a3a212013-08-30 19:43:59 +00001151 builder->fsEmitFunction(kFloat_GrSLType,
1152 "perlinnoise", SK_ARRAY_COUNT(gPerlinNoiseArgs),
1153 gPerlinNoiseArgs, noiseCode.c_str(), &noiseFuncName);
sugoi@google.comd537af52013-06-10 13:59:25 +00001154 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001155
sugoi@google.comd537af52013-06-10 13:59:25 +00001156 // There are rounding errors if the floor operation is not performed here
1157 builder->fsCodeAppendf("\n\t\tvec2 %s = floor((%s * vec3(%s, 1.0)).xy) * %s;",
commit-bot@chromium.org7ab7ca42013-08-28 15:59:13 +00001158 noiseVec, invMatrixUni, vCoords.c_str(), baseFrequencyUni);
sugoi@google.comd537af52013-06-10 13:59:25 +00001159
1160 // Clear the color accumulator
1161 builder->fsCodeAppendf("\n\t\t%s = vec4(0.0);", outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001162
1163 if (fStitchTiles) {
sugoi@google.comd537af52013-06-10 13:59:25 +00001164 // Set up TurbulenceInitial stitch values.
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001165 builder->fsCodeAppendf("\n\t\tvec2 %s = %s;", stitchData, stitchDataUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001166 }
sugoi@google.come3b4c502013-04-05 13:47:09 +00001167
sugoi@google.comd537af52013-06-10 13:59:25 +00001168 builder->fsCodeAppendf("\n\t\tfloat %s = 1.0;", ratio);
1169
1170 // Loop over all octaves
1171 builder->fsCodeAppendf("\n\t\tfor (int octave = 0; octave < %d; ++octave) {", fNumOctaves);
1172
1173 builder->fsCodeAppendf("\n\t\t\t%s += ", outputColor);
1174 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1175 builder->fsCodeAppend("abs(");
1176 }
1177 if (fStitchTiles) {
1178 builder->fsCodeAppendf(
1179 "vec4(\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s),"
1180 "\n\t\t\t\t%s(%s, %s, %s),\n\t\t\t\t%s(%s, %s, %s))",
1181 noiseFuncName.c_str(), chanCoordR, noiseVec, stitchData,
1182 noiseFuncName.c_str(), chanCoordG, noiseVec, stitchData,
1183 noiseFuncName.c_str(), chanCoordB, noiseVec, stitchData,
1184 noiseFuncName.c_str(), chanCoordA, noiseVec, stitchData);
1185 } else {
1186 builder->fsCodeAppendf(
1187 "vec4(\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s),"
1188 "\n\t\t\t\t%s(%s, %s),\n\t\t\t\t%s(%s, %s))",
1189 noiseFuncName.c_str(), chanCoordR, noiseVec,
1190 noiseFuncName.c_str(), chanCoordG, noiseVec,
1191 noiseFuncName.c_str(), chanCoordB, noiseVec,
1192 noiseFuncName.c_str(), chanCoordA, noiseVec);
1193 }
1194 if (fType != SkPerlinNoiseShader::kFractalNoise_Type) {
1195 builder->fsCodeAppendf(")"); // end of "abs("
1196 }
1197 builder->fsCodeAppendf(" * %s;", ratio);
1198
1199 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", noiseVec);
1200 builder->fsCodeAppendf("\n\t\t\t%s *= 0.5;", ratio);
1201
1202 if (fStitchTiles) {
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001203 builder->fsCodeAppendf("\n\t\t\t%s *= vec2(2.0);", stitchData);
sugoi@google.comd537af52013-06-10 13:59:25 +00001204 }
1205 builder->fsCodeAppend("\n\t\t}"); // end of the for loop on octaves
sugoi@google.come3b4c502013-04-05 13:47:09 +00001206
1207 if (fType == SkPerlinNoiseShader::kFractalNoise_Type) {
1208 // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult) + 1) / 2
1209 // by fractalNoise and (turbulenceFunctionResult) by turbulence.
sugoi@google.comd537af52013-06-10 13:59:25 +00001210 builder->fsCodeAppendf("\n\t\t%s = %s * vec4(0.5) + vec4(0.5);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001211 }
1212
sugoi@google.comd537af52013-06-10 13:59:25 +00001213 builder->fsCodeAppendf("\n\t\t%s.a *= %s;", outputColor, alphaUni);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001214
1215 // Clamp values
sugoi@google.comd537af52013-06-10 13:59:25 +00001216 builder->fsCodeAppendf("\n\t\t%s = clamp(%s, 0.0, 1.0);", outputColor, outputColor);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001217
1218 // Pre-multiply the result
sugoi@google.comd537af52013-06-10 13:59:25 +00001219 builder->fsCodeAppendf("\n\t\t%s = vec4(%s.rgb * %s.aaa, %s.a);\n",
sugoi@google.come3b4c502013-04-05 13:47:09 +00001220 outputColor, outputColor, outputColor, outputColor);
1221}
1222
sugoi@google.com4775cba2013-04-17 13:46:56 +00001223GrGLNoise::GrGLNoise(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect)
sugoi@google.come3b4c502013-04-05 13:47:09 +00001224 : INHERITED (factory)
1225 , fType(drawEffect.castEffect<GrPerlinNoiseEffect>().type())
1226 , fStitchTiles(drawEffect.castEffect<GrPerlinNoiseEffect>().stitchTiles())
bsalomon@google.com77af6802013-10-02 13:04:56 +00001227 , fNumOctaves(drawEffect.castEffect<GrPerlinNoiseEffect>().numOctaves()) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001228}
1229
sugoi@google.com4775cba2013-04-17 13:46:56 +00001230GrGLEffect::EffectKey GrGLNoise::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001231 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1232
1233 EffectKey key = turbulence.numOctaves();
1234
1235 key = key << 3; // Make room for next 3 bits
1236
1237 switch (turbulence.type()) {
1238 case SkPerlinNoiseShader::kFractalNoise_Type:
1239 key |= 0x1;
1240 break;
1241 case SkPerlinNoiseShader::kTurbulence_Type:
1242 key |= 0x2;
1243 break;
1244 default:
1245 // leave key at 0
1246 break;
1247 }
1248
1249 if (turbulence.stitchTiles()) {
1250 key |= 0x4; // Flip the 3rd bit if tile stitching is on
1251 }
1252
bsalomon@google.com77af6802013-10-02 13:04:56 +00001253 return key;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001254}
1255
sugoi@google.com4775cba2013-04-17 13:46:56 +00001256void GrGLNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001257 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1258
1259 const SkVector& baseFrequency = turbulence.baseFrequency();
1260 uman.set2f(fBaseFrequencyUni, baseFrequency.fX, baseFrequency.fY);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001261 uman.set1f(fAlphaUni, SkScalarDiv(SkIntToScalar(turbulence.alpha()), SkIntToScalar(255)));
1262
1263 SkMatrix m = turbulence.matrix();
bsalomon@google.com77af6802013-10-02 13:04:56 +00001264 m.postTranslate(-SK_Scalar1, -SK_Scalar1);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001265 SkMatrix invM;
1266 if (!m.invert(&invM)) {
1267 invM.reset();
1268 } else {
1269 invM.postConcat(invM); // Square the matrix
1270 }
1271 uman.setSkMatrix(fInvMatrixUni, invM);
sugoi@google.come3b4c502013-04-05 13:47:09 +00001272}
1273
sugoi@google.com4775cba2013-04-17 13:46:56 +00001274void GrGLPerlinNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1275 INHERITED::setData(uman, drawEffect);
1276
1277 const GrPerlinNoiseEffect& turbulence = drawEffect.castEffect<GrPerlinNoiseEffect>();
1278 if (turbulence.stitchTiles()) {
1279 const SkPerlinNoiseShader::StitchData& stitchData = turbulence.stitchData();
commit-bot@chromium.org98393202013-07-04 18:13:05 +00001280 uman.set2f(fStitchDataUni, SkIntToScalar(stitchData.fWidth),
1281 SkIntToScalar(stitchData.fHeight));
sugoi@google.com4775cba2013-04-17 13:46:56 +00001282 }
1283}
1284
1285void GrGLSimplexNoise::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) {
1286 INHERITED::setData(uman, drawEffect);
1287
1288 const GrSimplexNoiseEffect& turbulence = drawEffect.castEffect<GrSimplexNoiseEffect>();
1289 uman.set1f(fSeedUni, turbulence.seed());
1290}
1291
sugoi@google.come3b4c502013-04-05 13:47:09 +00001292/////////////////////////////////////////////////////////////////////
1293
1294GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
sugoi@google.come3b4c502013-04-05 13:47:09 +00001295 SkASSERT(NULL != context);
1296
1297 // Either we don't stitch tiles, either we have a valid tile size
1298 SkASSERT(!fStitchTiles || !fTileSize.isEmpty());
1299
sugoi@google.com4775cba2013-04-17 13:46:56 +00001300#ifdef SK_USE_SIMPLEX_NOISE
1301 // Simplex noise is currently disabled but can be enabled by defining SK_USE_SIMPLEX_NOISE
1302 sk_ignore_unused_variable(context);
1303 GrEffectRef* effect =
1304 GrSimplexNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
1305 fNumOctaves, fStitchTiles, fSeed,
1306 this->getLocalMatrix(), paint.getAlpha());
1307#else
sugoi@google.come3b4c502013-04-05 13:47:09 +00001308 GrTexture* permutationsTexture = GrLockAndRefCachedBitmapTexture(
1309 context, *fPaintingData->getPermutationsBitmap(), NULL);
1310 GrTexture* noiseTexture = GrLockAndRefCachedBitmapTexture(
1311 context, *fPaintingData->getNoiseBitmap(), NULL);
1312
1313 GrEffectRef* effect = (NULL != permutationsTexture) && (NULL != noiseTexture) ?
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001314 GrPerlinNoiseEffect::Create(fType, fPaintingData->fBaseFrequency,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001315 fNumOctaves, fStitchTiles,
1316 fPaintingData->fStitchDataInit,
skia.committer@gmail.comcff02432013-04-06 07:01:10 +00001317 permutationsTexture, noiseTexture,
sugoi@google.come3b4c502013-04-05 13:47:09 +00001318 this->getLocalMatrix(), paint.getAlpha()) :
1319 NULL;
1320
1321 // Unlock immediately, this is not great, but we don't have a way of
1322 // knowing when else to unlock it currently. TODO: Remove this when
1323 // unref becomes the unlock replacement for all types of textures.
1324 if (NULL != permutationsTexture) {
1325 GrUnlockAndUnrefCachedBitmapTexture(permutationsTexture);
1326 }
1327 if (NULL != noiseTexture) {
1328 GrUnlockAndUnrefCachedBitmapTexture(noiseTexture);
1329 }
sugoi@google.com4775cba2013-04-17 13:46:56 +00001330#endif
sugoi@google.come3b4c502013-04-05 13:47:09 +00001331
1332 return effect;
sugoi@google.come3b4c502013-04-05 13:47:09 +00001333}
1334
1335#else
1336
1337GrEffectRef* SkPerlinNoiseShader::asNewEffect(GrContext*, const SkPaint&) const {
1338 SkDEBUGFAIL("Should not call in GPU-less build");
sugoi@google.come3b4c502013-04-05 13:47:09 +00001339 return NULL;
1340}
1341
1342#endif
1343
1344#ifdef SK_DEVELOPER
1345void SkPerlinNoiseShader::toString(SkString* str) const {
1346 str->append("SkPerlinNoiseShader: (");
1347
1348 str->append("type: ");
1349 switch (fType) {
1350 case kFractalNoise_Type:
1351 str->append("\"fractal noise\"");
1352 break;
1353 case kTurbulence_Type:
1354 str->append("\"turbulence\"");
1355 break;
1356 default:
1357 str->append("\"unknown\"");
1358 break;
1359 }
1360 str->append(" base frequency: (");
1361 str->appendScalar(fBaseFrequencyX);
1362 str->append(", ");
1363 str->appendScalar(fBaseFrequencyY);
1364 str->append(") number of octaves: ");
1365 str->appendS32(fNumOctaves);
1366 str->append(" seed: ");
1367 str->appendScalar(fSeed);
1368 str->append(" stitch tiles: ");
1369 str->append(fStitchTiles ? "true " : "false ");
1370
1371 this->INHERITED::toString(str);
1372
1373 str->append(")");
1374}
1375#endif