1 /*
2  * Copyright 2011 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 "SkColorMatrixFilterRowMajor255.h"
9 #include "SkColorData.h"
10 #include "SkNx.h"
11 #include "SkPM4fPriv.h"
12 #include "SkRasterPipeline.h"
13 #include "SkReadBuffer.h"
14 #include "SkRefCnt.h"
15 #include "SkString.h"
16 #include "SkUnPreMultiply.h"
17 #include "SkWriteBuffer.h"
18 
transpose_and_scale01(float dst[20],const float src[20])19 static void transpose_and_scale01(float dst[20], const float src[20]) {
20     const float* srcR = src + 0;
21     const float* srcG = src + 5;
22     const float* srcB = src + 10;
23     const float* srcA = src + 15;
24 
25     for (int i = 0; i < 16; i += 4) {
26         dst[i + 0] = *srcR++;
27         dst[i + 1] = *srcG++;
28         dst[i + 2] = *srcB++;
29         dst[i + 3] = *srcA++;
30     }
31     // Might as well scale these translates down to [0,1] here instead of every filter call.
32     dst[16] = *srcR * (1/255.0f);
33     dst[17] = *srcG * (1/255.0f);
34     dst[18] = *srcB * (1/255.0f);
35     dst[19] = *srcA * (1/255.0f);
36 }
37 
initState()38 void SkColorMatrixFilterRowMajor255::initState() {
39     transpose_and_scale01(fTranspose, fMatrix);
40 
41     const float* array = fMatrix;
42 
43     // check if we have to munge Alpha
44     bool changesAlpha = (array[15] || array[16] || array[17] || (array[18] - 1) || array[19]);
45     bool usesAlpha = (array[3] || array[8] || array[13]);
46 
47     if (changesAlpha || usesAlpha) {
48         fFlags = changesAlpha ? 0 : kAlphaUnchanged_Flag;
49     } else {
50         fFlags = kAlphaUnchanged_Flag;
51     }
52 }
53 
54 ///////////////////////////////////////////////////////////////////////////////
55 
SkColorMatrixFilterRowMajor255(const SkScalar array[20])56 SkColorMatrixFilterRowMajor255::SkColorMatrixFilterRowMajor255(const SkScalar array[20]) {
57     memcpy(fMatrix, array, 20 * sizeof(SkScalar));
58     this->initState();
59 }
60 
getFlags() const61 uint32_t SkColorMatrixFilterRowMajor255::getFlags() const {
62     return this->INHERITED::getFlags() | fFlags;
63 }
64 
65 ///////////////////////////////////////////////////////////////////////////////
66 
flatten(SkWriteBuffer & buffer) const67 void SkColorMatrixFilterRowMajor255::flatten(SkWriteBuffer& buffer) const {
68     SkASSERT(sizeof(fMatrix)/sizeof(SkScalar) == 20);
69     buffer.writeScalarArray(fMatrix, 20);
70 }
71 
CreateProc(SkReadBuffer & buffer)72 sk_sp<SkFlattenable> SkColorMatrixFilterRowMajor255::CreateProc(SkReadBuffer& buffer) {
73     SkScalar matrix[20];
74     if (buffer.readScalarArray(matrix, 20)) {
75         return sk_make_sp<SkColorMatrixFilterRowMajor255>(matrix);
76     }
77     return nullptr;
78 }
79 
asColorMatrix(SkScalar matrix[20]) const80 bool SkColorMatrixFilterRowMajor255::asColorMatrix(SkScalar matrix[20]) const {
81     if (matrix) {
82         memcpy(matrix, fMatrix, 20 * sizeof(SkScalar));
83     }
84     return true;
85 }
86 
87 ///////////////////////////////////////////////////////////////////////////////
88 //  This code was duplicated from src/effects/SkColorMatrixc.cpp in order to be used in core.
89 //////
90 
91 // To detect if we need to apply clamping after applying a matrix, we check if
92 // any output component might go outside of [0, 255] for any combination of
93 // input components in [0..255].
94 // Each output component is an affine transformation of the input component, so
95 // the minimum and maximum values are for any combination of minimum or maximum
96 // values of input components (i.e. 0 or 255).
97 // E.g. if R' = x*R + y*G + z*B + w*A + t
98 // Then the maximum value will be for R=255 if x>0 or R=0 if x<0, and the
99 // minimum value will be for R=0 if x>0 or R=255 if x<0.
100 // Same goes for all components.
component_needs_clamping(const SkScalar row[5])101 static bool component_needs_clamping(const SkScalar row[5]) {
102     SkScalar maxValue = row[4] / 255;
103     SkScalar minValue = row[4] / 255;
104     for (int i = 0; i < 4; ++i) {
105         if (row[i] > 0)
106             maxValue += row[i];
107         else
108             minValue += row[i];
109     }
110     return (maxValue > 1) || (minValue < 0);
111 }
112 
needs_clamping(const SkScalar matrix[20])113 static bool needs_clamping(const SkScalar matrix[20]) {
114     return component_needs_clamping(matrix)
115         || component_needs_clamping(matrix+5)
116         || component_needs_clamping(matrix+10)
117         || component_needs_clamping(matrix+15);
118 }
119 
set_concat(SkScalar result[20],const SkScalar outer[20],const SkScalar inner[20])120 static void set_concat(SkScalar result[20], const SkScalar outer[20], const SkScalar inner[20]) {
121     int index = 0;
122     for (int j = 0; j < 20; j += 5) {
123         for (int i = 0; i < 4; i++) {
124             result[index++] =   outer[j + 0] * inner[i + 0] +
125                                 outer[j + 1] * inner[i + 5] +
126                                 outer[j + 2] * inner[i + 10] +
127                                 outer[j + 3] * inner[i + 15];
128         }
129         result[index++] =   outer[j + 0] * inner[4] +
130                             outer[j + 1] * inner[9] +
131                             outer[j + 2] * inner[14] +
132                             outer[j + 3] * inner[19] +
133                             outer[j + 4];
134     }
135 }
136 
137 ///////////////////////////////////////////////////////////////////////////////
138 //  End duplication
139 //////
140 
onAppendStages(SkRasterPipeline * p,SkColorSpace * dst,SkArenaAlloc * scratch,bool shaderIsOpaque) const141 void SkColorMatrixFilterRowMajor255::onAppendStages(SkRasterPipeline* p,
142                                                     SkColorSpace* dst,
143                                                     SkArenaAlloc* scratch,
144                                                     bool shaderIsOpaque) const {
145     bool willStayOpaque = shaderIsOpaque && (fFlags & kAlphaUnchanged_Flag);
146     bool needsClamp0 = false,
147          needsClamp1 = false;
148     for (int i = 0; i < 4; i++) {
149         SkScalar min = fTranspose[i+16],
150                  max = fTranspose[i+16];
151         (fTranspose[i+ 0] < 0 ? min : max) += fTranspose[i+ 0];
152         (fTranspose[i+ 4] < 0 ? min : max) += fTranspose[i+ 4];
153         (fTranspose[i+ 8] < 0 ? min : max) += fTranspose[i+ 8];
154         (fTranspose[i+12] < 0 ? min : max) += fTranspose[i+12];
155         needsClamp0 = needsClamp0 || min < 0;
156         needsClamp1 = needsClamp1 || max > 1;
157     }
158 
159     if (!shaderIsOpaque) { p->append(SkRasterPipeline::unpremul); }
160     if (           true) { p->append(SkRasterPipeline::matrix_4x5, fTranspose); }
161     if (    needsClamp0) { p->append(SkRasterPipeline::clamp_0); }
162     if (    needsClamp1) { p->append(SkRasterPipeline::clamp_1); }
163     if (!willStayOpaque) { p->append(SkRasterPipeline::premul); }
164 }
165 
166 sk_sp<SkColorFilter>
onMakeComposed(sk_sp<SkColorFilter> innerFilter) const167 SkColorMatrixFilterRowMajor255::onMakeComposed(sk_sp<SkColorFilter> innerFilter) const {
168     SkScalar innerMatrix[20];
169     if (innerFilter->asColorMatrix(innerMatrix) && !needs_clamping(innerMatrix)) {
170         SkScalar concat[20];
171         set_concat(concat, fMatrix, innerMatrix);
172         return sk_make_sp<SkColorMatrixFilterRowMajor255>(concat);
173     }
174     return nullptr;
175 }
176 
177 #if SK_SUPPORT_GPU
178 #include "GrFragmentProcessor.h"
179 #include "glsl/GrGLSLFragmentProcessor.h"
180 #include "glsl/GrGLSLFragmentShaderBuilder.h"
181 #include "glsl/GrGLSLProgramDataManager.h"
182 #include "glsl/GrGLSLUniformHandler.h"
183 
184 class ColorMatrixEffect : public GrFragmentProcessor {
185 public:
Make(const SkScalar matrix[20])186     static std::unique_ptr<GrFragmentProcessor> Make(const SkScalar matrix[20]) {
187         return std::unique_ptr<GrFragmentProcessor>(new ColorMatrixEffect(matrix));
188     }
189 
name() const190     const char* name() const override { return "Color Matrix"; }
191 
192     GR_DECLARE_FRAGMENT_PROCESSOR_TEST
193 
clone() const194     std::unique_ptr<GrFragmentProcessor> clone() const override { return Make(fMatrix); }
195 
196 private:
197     class GLSLProcessor : public GrGLSLFragmentProcessor {
198     public:
199         // this class always generates the same code.
GenKey(const GrProcessor &,const GrShaderCaps &,GrProcessorKeyBuilder *)200         static void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder*) {}
201 
emitCode(EmitArgs & args)202         void emitCode(EmitArgs& args) override {
203             GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
204             fMatrixHandle = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf4x4_GrSLType,
205                                                        "ColorMatrix");
206             fVectorHandle = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf4_GrSLType,
207                                                        "ColorMatrixVector");
208 
209             if (nullptr == args.fInputColor) {
210                 // could optimize this case, but we aren't for now.
211                 args.fInputColor = "half4(1)";
212             }
213             GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
214             // The max() is to guard against 0 / 0 during unpremul when the incoming color is
215             // transparent black.
216             fragBuilder->codeAppendf("\thalf nonZeroAlpha = max(%s.a, 0.00001);\n",
217                                      args.fInputColor);
218             fragBuilder->codeAppendf("\t%s = %s * half4(%s.rgb / nonZeroAlpha, nonZeroAlpha) + "
219                                      "%s;\n",
220                                      args.fOutputColor,
221                                      uniformHandler->getUniformCStr(fMatrixHandle),
222                                      args.fInputColor,
223                                      uniformHandler->getUniformCStr(fVectorHandle));
224             fragBuilder->codeAppendf("\t%s = clamp(%s, 0.0, 1.0);\n",
225                                      args.fOutputColor, args.fOutputColor);
226             fragBuilder->codeAppendf("\t%s.rgb *= %s.a;\n", args.fOutputColor, args.fOutputColor);
227         }
228 
229     protected:
onSetData(const GrGLSLProgramDataManager & uniManager,const GrFragmentProcessor & proc)230         void onSetData(const GrGLSLProgramDataManager& uniManager,
231                        const GrFragmentProcessor& proc) override {
232             const ColorMatrixEffect& cme = proc.cast<ColorMatrixEffect>();
233             const float* m = cme.fMatrix;
234             // The GL matrix is transposed from SkColorMatrix.
235             float mt[]  = {
236                 m[0], m[5], m[10], m[15],
237                 m[1], m[6], m[11], m[16],
238                 m[2], m[7], m[12], m[17],
239                 m[3], m[8], m[13], m[18],
240             };
241             static const float kScale = 1.0f / 255.0f;
242             float vec[] = {
243                 m[4] * kScale, m[9] * kScale, m[14] * kScale, m[19] * kScale,
244             };
245             uniManager.setMatrix4fv(fMatrixHandle, 1, mt);
246             uniManager.set4fv(fVectorHandle, 1, vec);
247         }
248 
249     private:
250         GrGLSLProgramDataManager::UniformHandle fMatrixHandle;
251         GrGLSLProgramDataManager::UniformHandle fVectorHandle;
252 
253         typedef GrGLSLFragmentProcessor INHERITED;
254     };
255 
256     // We could implement the constant input->constant output optimization but haven't. Other
257     // optimizations would be matrix-dependent.
ColorMatrixEffect(const SkScalar matrix[20])258     ColorMatrixEffect(const SkScalar matrix[20])
259     : INHERITED(kColorMatrixEffect_ClassID, kNone_OptimizationFlags) {
260         memcpy(fMatrix, matrix, sizeof(SkScalar) * 20);
261     }
262 
onCreateGLSLInstance() const263     GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
264         return new GLSLProcessor;
265     }
266 
onGetGLSLProcessorKey(const GrShaderCaps & caps,GrProcessorKeyBuilder * b) const267     virtual void onGetGLSLProcessorKey(const GrShaderCaps& caps,
268                                        GrProcessorKeyBuilder* b) const override {
269         GLSLProcessor::GenKey(*this, caps, b);
270     }
271 
onIsEqual(const GrFragmentProcessor & s) const272     bool onIsEqual(const GrFragmentProcessor& s) const override {
273         const ColorMatrixEffect& cme = s.cast<ColorMatrixEffect>();
274         return 0 == memcmp(fMatrix, cme.fMatrix, sizeof(fMatrix));
275     }
276 
277     SkScalar fMatrix[20];
278 
279     typedef GrFragmentProcessor INHERITED;
280 };
281 
282 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(ColorMatrixEffect);
283 
284 #if GR_TEST_UTILS
TestCreate(GrProcessorTestData * d)285 std::unique_ptr<GrFragmentProcessor> ColorMatrixEffect::TestCreate(GrProcessorTestData* d) {
286     SkScalar colorMatrix[20];
287     for (size_t i = 0; i < SK_ARRAY_COUNT(colorMatrix); ++i) {
288         colorMatrix[i] = d->fRandom->nextSScalar1();
289     }
290     return ColorMatrixEffect::Make(colorMatrix);
291 }
292 
293 #endif
294 
asFragmentProcessor(GrContext *,const GrColorSpaceInfo &) const295 std::unique_ptr<GrFragmentProcessor> SkColorMatrixFilterRowMajor255::asFragmentProcessor(
296         GrContext*, const GrColorSpaceInfo&) const {
297     return ColorMatrixEffect::Make(fMatrix);
298 }
299 
300 #endif
301 
302 #ifndef SK_IGNORE_TO_STRING
toString(SkString * str) const303 void SkColorMatrixFilterRowMajor255::toString(SkString* str) const {
304     str->append("SkColorMatrixFilterRowMajor255: ");
305 
306     str->append("matrix: (");
307     for (int i = 0; i < 20; ++i) {
308         str->appendScalar(fMatrix[i]);
309         if (i < 19) {
310             str->append(", ");
311         }
312     }
313     str->append(")");
314 }
315 #endif
316 
317 ///////////////////////////////////////////////////////////////////////////////
318 
MakeMatrixFilterRowMajor255(const SkScalar array[20])319 sk_sp<SkColorFilter> SkColorFilter::MakeMatrixFilterRowMajor255(const SkScalar array[20]) {
320     return sk_sp<SkColorFilter>(new SkColorMatrixFilterRowMajor255(array));
321 }
322 
323 ///////////////////////////////////////////////////////////////////////////////
324 
325 sk_sp<SkColorFilter>
MakeSingleChannelOutput(const SkScalar row[5])326 SkColorMatrixFilterRowMajor255::MakeSingleChannelOutput(const SkScalar row[5]) {
327     SkASSERT(row);
328     auto cf = sk_make_sp<SkColorMatrixFilterRowMajor255>();
329     static_assert(sizeof(SkScalar) * 5 * 4 == sizeof(cf->fMatrix), "sizes don't match");
330     for (int i = 0; i < 4; ++i) {
331         memcpy(cf->fMatrix + 5 * i, row, sizeof(SkScalar) * 5);
332     }
333     cf->initState();
334     return cf;
335 }
336