blob: 9106a279c0802fc9830b6bf63038d10c7d58e429 [file] [log] [blame]
bsalomon86100022016-02-01 12:09:07 -08001/*
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 "SkColorPriv.h"
10#include "SkNx.h"
11#include "SkReadBuffer.h"
12#include "SkWriteBuffer.h"
13#include "SkUnPreMultiply.h"
14#include "SkString.h"
15
16#define SK_PMORDER_INDEX_A (SK_A32_SHIFT / 8)
17#define SK_PMORDER_INDEX_R (SK_R32_SHIFT / 8)
18#define SK_PMORDER_INDEX_G (SK_G32_SHIFT / 8)
19#define SK_PMORDER_INDEX_B (SK_B32_SHIFT / 8)
20
21static void transpose_to_pmorder(float dst[20], const float src[20]) {
22 const float* srcR = src + 0;
23 const float* srcG = src + 5;
24 const float* srcB = src + 10;
25 const float* srcA = src + 15;
26
27 for (int i = 0; i < 20; i += 4) {
28 dst[i + SK_PMORDER_INDEX_A] = *srcA++;
29 dst[i + SK_PMORDER_INDEX_R] = *srcR++;
30 dst[i + SK_PMORDER_INDEX_G] = *srcG++;
31 dst[i + SK_PMORDER_INDEX_B] = *srcB++;
32 }
33}
34
bsalomonf267c1e2016-02-01 13:16:14 -080035void SkColorMatrixFilterRowMajor255::initState() {
36 transpose_to_pmorder(fTranspose, fMatrix);
bsalomon86100022016-02-01 12:09:07 -080037
38 const float* array = fMatrix;
39
40 // check if we have to munge Alpha
41 bool changesAlpha = (array[15] || array[16] || array[17] || (array[18] - 1) || array[19]);
42 bool usesAlpha = (array[3] || array[8] || array[13]);
43
44 if (changesAlpha || usesAlpha) {
45 fFlags = changesAlpha ? 0 : kAlphaUnchanged_Flag;
46 } else {
47 fFlags = kAlphaUnchanged_Flag;
48 }
49 fFlags |= kSupports4f_Flag;
50}
51
52///////////////////////////////////////////////////////////////////////////////
53
54SkColorMatrixFilterRowMajor255::SkColorMatrixFilterRowMajor255(const SkScalar array[20]) {
55 memcpy(fMatrix, array, 20 * sizeof(SkScalar));
bsalomonf267c1e2016-02-01 13:16:14 -080056 this->initState();
bsalomon86100022016-02-01 12:09:07 -080057}
58
59uint32_t SkColorMatrixFilterRowMajor255::getFlags() const {
60 return this->INHERITED::getFlags() | fFlags;
61}
62
63static Sk4f scale_rgb(float scale) {
64 static_assert(SkPM4f::A == 3, "Alpha is lane 3");
65 return Sk4f(scale, scale, scale, 1);
66}
67
68static Sk4f premul(const Sk4f& x) {
69 return x * scale_rgb(x.kth<SkPM4f::A>());
70}
71
72static Sk4f unpremul(const Sk4f& x) {
73 return x * scale_rgb(1 / x.kth<SkPM4f::A>()); // TODO: fast/approx invert?
74}
75
76static Sk4f clamp_0_1(const Sk4f& x) {
77 return Sk4f::Max(Sk4f::Min(x, Sk4f(1)), Sk4f(0));
78}
79
80static SkPMColor round(const Sk4f& x) {
81 SkPMColor c;
82 SkNx_cast<uint8_t>(x * Sk4f(255) + Sk4f(0.5f)).store(&c);
83 return c;
84}
85
86template <typename Adaptor, typename T>
87void filter_span(const float array[], const T src[], int count, T dst[]) {
88 // c0-c3 are already in [0,1].
89 const Sk4f c0 = Sk4f::Load(array + 0);
90 const Sk4f c1 = Sk4f::Load(array + 4);
91 const Sk4f c2 = Sk4f::Load(array + 8);
92 const Sk4f c3 = Sk4f::Load(array + 12);
93 // c4 (the translate vector) is in [0, 255]. Bring it back to [0,1].
94 const Sk4f c4 = Sk4f::Load(array + 16)*Sk4f(1.0f/255);
95
96 // todo: we could cache this in the constructor...
97 T matrix_translate_pmcolor = Adaptor::From4f(premul(clamp_0_1(c4)));
98
99 for (int i = 0; i < count; i++) {
100 Sk4f srcf = Adaptor::To4f(src[i]);
101 float srcA = srcf.kth<SkPM4f::A>();
102
103 if (0 == srcA) {
104 dst[i] = matrix_translate_pmcolor;
105 continue;
106 }
107 if (1 != srcA) {
108 srcf = unpremul(srcf);
109 }
110
111 Sk4f r4 = SkNx_dup<SK_R32_SHIFT/8>(srcf);
112 Sk4f g4 = SkNx_dup<SK_G32_SHIFT/8>(srcf);
113 Sk4f b4 = SkNx_dup<SK_B32_SHIFT/8>(srcf);
114 Sk4f a4 = SkNx_dup<SK_A32_SHIFT/8>(srcf);
115
116 // apply matrix
117 Sk4f dst4 = c0 * r4 + c1 * g4 + c2 * b4 + c3 * a4 + c4;
118
119 dst[i] = Adaptor::From4f(premul(clamp_0_1(dst4)));
120 }
121}
122
123struct SkPMColorAdaptor {
124 static SkPMColor From4f(const Sk4f& c4) {
125 return round(c4);
126 }
127 static Sk4f To4f(SkPMColor c) {
128 return SkNx_cast<float>(Sk4b::Load(&c)) * Sk4f(1.0f/255);
129 }
130};
131void SkColorMatrixFilterRowMajor255::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) const {
132 filter_span<SkPMColorAdaptor>(fTranspose, src, count, dst);
133}
134
135struct SkPM4fAdaptor {
136 static SkPM4f From4f(const Sk4f& c4) {
137 SkPM4f c;
138 c4.store(&c);
139 return c;
140 }
141 static Sk4f To4f(const SkPM4f& c) {
142 return Sk4f::Load(&c);
143 }
144};
145void SkColorMatrixFilterRowMajor255::filterSpan4f(const SkPM4f src[], int count, SkPM4f dst[]) const {
146 filter_span<SkPM4fAdaptor>(fTranspose, src, count, dst);
147}
148
149///////////////////////////////////////////////////////////////////////////////
150
151void SkColorMatrixFilterRowMajor255::flatten(SkWriteBuffer& buffer) const {
152 SkASSERT(sizeof(fMatrix)/sizeof(SkScalar) == 20);
153 buffer.writeScalarArray(fMatrix, 20);
154}
155
156SkFlattenable* SkColorMatrixFilterRowMajor255::CreateProc(SkReadBuffer& buffer) {
157 SkScalar matrix[20];
158 if (buffer.readScalarArray(matrix, 20)) {
159 return new SkColorMatrixFilterRowMajor255(matrix);
160 }
161 return nullptr;
162}
163
164bool SkColorMatrixFilterRowMajor255::asColorMatrix(SkScalar matrix[20]) const {
165 if (matrix) {
166 memcpy(matrix, fMatrix, 20 * sizeof(SkScalar));
167 }
168 return true;
169}
170
171///////////////////////////////////////////////////////////////////////////////
172// This code was duplicated from src/effects/SkColorMatrixc.cpp in order to be used in core.
173//////
174
175// To detect if we need to apply clamping after applying a matrix, we check if
176// any output component might go outside of [0, 255] for any combination of
177// input components in [0..255].
178// Each output component is an affine transformation of the input component, so
179// the minimum and maximum values are for any combination of minimum or maximum
180// values of input components (i.e. 0 or 255).
181// E.g. if R' = x*R + y*G + z*B + w*A + t
182// Then the maximum value will be for R=255 if x>0 or R=0 if x<0, and the
183// minimum value will be for R=0 if x>0 or R=255 if x<0.
184// Same goes for all components.
185static bool component_needs_clamping(const SkScalar row[5]) {
186 SkScalar maxValue = row[4] / 255;
187 SkScalar minValue = row[4] / 255;
188 for (int i = 0; i < 4; ++i) {
189 if (row[i] > 0)
190 maxValue += row[i];
191 else
192 minValue += row[i];
193 }
194 return (maxValue > 1) || (minValue < 0);
195}
196
197static bool needs_clamping(const SkScalar matrix[20]) {
198 return component_needs_clamping(matrix)
199 || component_needs_clamping(matrix+5)
200 || component_needs_clamping(matrix+10)
201 || component_needs_clamping(matrix+15);
202}
203
204static void set_concat(SkScalar result[20], const SkScalar outer[20], const SkScalar inner[20]) {
205 int index = 0;
206 for (int j = 0; j < 20; j += 5) {
207 for (int i = 0; i < 4; i++) {
208 result[index++] = outer[j + 0] * inner[i + 0] +
209 outer[j + 1] * inner[i + 5] +
210 outer[j + 2] * inner[i + 10] +
211 outer[j + 3] * inner[i + 15];
212 }
213 result[index++] = outer[j + 0] * inner[4] +
214 outer[j + 1] * inner[9] +
215 outer[j + 2] * inner[14] +
216 outer[j + 3] * inner[19] +
217 outer[j + 4];
218 }
219}
220
221///////////////////////////////////////////////////////////////////////////////
222// End duplication
223//////
224
225SkColorFilter* SkColorMatrixFilterRowMajor255::newComposed(const SkColorFilter* innerFilter) const {
226 SkScalar innerMatrix[20];
227 if (innerFilter->asColorMatrix(innerMatrix) && !needs_clamping(innerMatrix)) {
228 SkScalar concat[20];
229 set_concat(concat, fMatrix, innerMatrix);
230 return new SkColorMatrixFilterRowMajor255(concat);
231 }
232 return nullptr;
233}
234
235#if SK_SUPPORT_GPU
236#include "GrFragmentProcessor.h"
237#include "GrInvariantOutput.h"
238#include "glsl/GrGLSLFragmentProcessor.h"
239#include "glsl/GrGLSLFragmentShaderBuilder.h"
240#include "glsl/GrGLSLProgramDataManager.h"
241#include "glsl/GrGLSLUniformHandler.h"
242
243class ColorMatrixEffect : public GrFragmentProcessor {
244public:
245 static const GrFragmentProcessor* Create(const SkScalar matrix[20]) {
246 return new ColorMatrixEffect(matrix);
247 }
248
249 const char* name() const override { return "Color Matrix"; }
250
251 GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
252
253 class GLSLProcessor : public GrGLSLFragmentProcessor {
254 public:
255 // this class always generates the same code.
256 static void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder* b) {}
257
258 GLSLProcessor(const GrProcessor&) {}
259
260 virtual void emitCode(EmitArgs& args) override {
261 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
262 fMatrixHandle = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility,
263 kMat44f_GrSLType, kDefault_GrSLPrecision,
264 "ColorMatrix");
265 fVectorHandle = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility,
266 kVec4f_GrSLType, kDefault_GrSLPrecision,
267 "ColorMatrixVector");
268
269 if (nullptr == args.fInputColor) {
270 // could optimize this case, but we aren't for now.
271 args.fInputColor = "vec4(1)";
272 }
273 GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
274 // The max() is to guard against 0 / 0 during unpremul when the incoming color is
275 // transparent black.
276 fragBuilder->codeAppendf("\tfloat nonZeroAlpha = max(%s.a, 0.00001);\n",
277 args.fInputColor);
278 fragBuilder->codeAppendf("\t%s = %s * vec4(%s.rgb / nonZeroAlpha, nonZeroAlpha) + %s;\n",
279 args.fOutputColor,
280 uniformHandler->getUniformCStr(fMatrixHandle),
281 args.fInputColor,
282 uniformHandler->getUniformCStr(fVectorHandle));
283 fragBuilder->codeAppendf("\t%s = clamp(%s, 0.0, 1.0);\n",
284 args.fOutputColor, args.fOutputColor);
285 fragBuilder->codeAppendf("\t%s.rgb *= %s.a;\n", args.fOutputColor, args.fOutputColor);
286 }
287
288 protected:
289 virtual void onSetData(const GrGLSLProgramDataManager& uniManager,
290 const GrProcessor& proc) override {
291 const ColorMatrixEffect& cme = proc.cast<ColorMatrixEffect>();
292 const float* m = cme.fMatrix;
293 // The GL matrix is transposed from SkColorMatrix.
294 float mt[] = {
295 m[0], m[5], m[10], m[15],
296 m[1], m[6], m[11], m[16],
297 m[2], m[7], m[12], m[17],
298 m[3], m[8], m[13], m[18],
299 };
300 static const float kScale = 1.0f / 255.0f;
301 float vec[] = {
302 m[4] * kScale, m[9] * kScale, m[14] * kScale, m[19] * kScale,
303 };
304 uniManager.setMatrix4fv(fMatrixHandle, 1, mt);
305 uniManager.set4fv(fVectorHandle, 1, vec);
306 }
307
308 private:
309 GrGLSLProgramDataManager::UniformHandle fMatrixHandle;
310 GrGLSLProgramDataManager::UniformHandle fVectorHandle;
311
312 typedef GrGLSLFragmentProcessor INHERITED;
313 };
314
315private:
316 ColorMatrixEffect(const SkScalar matrix[20]) {
317 memcpy(fMatrix, matrix, sizeof(SkScalar) * 20);
318 this->initClassID<ColorMatrixEffect>();
319 }
320
321 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
322 return new GLSLProcessor(*this);
323 }
324
325 virtual void onGetGLSLProcessorKey(const GrGLSLCaps& caps,
326 GrProcessorKeyBuilder* b) const override {
327 GLSLProcessor::GenKey(*this, caps, b);
328 }
329
330 bool onIsEqual(const GrFragmentProcessor& s) const override {
331 const ColorMatrixEffect& cme = s.cast<ColorMatrixEffect>();
332 return 0 == memcmp(fMatrix, cme.fMatrix, sizeof(fMatrix));
333 }
334
335 void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
336 // We only bother to check whether the alpha channel will be constant. If SkColorMatrix had
337 // type flags it might be worth checking the other components.
338
339 // The matrix is defined such the 4th row determines the output alpha. The first four
340 // columns of that row multiply the input r, g, b, and a, respectively, and the last column
341 // is the "translation".
342 static const uint32_t kRGBAFlags[] = {
343 kR_GrColorComponentFlag,
344 kG_GrColorComponentFlag,
345 kB_GrColorComponentFlag,
346 kA_GrColorComponentFlag
347 };
348 static const int kShifts[] = {
349 GrColor_SHIFT_R, GrColor_SHIFT_G, GrColor_SHIFT_B, GrColor_SHIFT_A,
350 };
351 enum {
352 kAlphaRowStartIdx = 15,
353 kAlphaRowTranslateIdx = 19,
354 };
355
356 SkScalar outputA = 0;
357 for (int i = 0; i < 4; ++i) {
358 // If any relevant component of the color to be passed through the matrix is non-const
359 // then we can't know the final result.
360 if (0 != fMatrix[kAlphaRowStartIdx + i]) {
361 if (!(inout->validFlags() & kRGBAFlags[i])) {
362 inout->setToUnknown(GrInvariantOutput::kWill_ReadInput);
363 return;
364 } else {
365 uint32_t component = (inout->color() >> kShifts[i]) & 0xFF;
366 outputA += fMatrix[kAlphaRowStartIdx + i] * component;
367 }
368 }
369 }
370 outputA += fMatrix[kAlphaRowTranslateIdx];
371 // We pin the color to [0,1]. This would happen to the *final* color output from the frag
372 // shader but currently the effect does not pin its own output. So in the case of over/
373 // underflow this may deviate from the actual result. Maybe the effect should pin its
374 // result if the matrix could over/underflow for any component?
375 inout->setToOther(kA_GrColorComponentFlag,
376 static_cast<uint8_t>(SkScalarPin(outputA, 0, 255)) << GrColor_SHIFT_A,
377 GrInvariantOutput::kWill_ReadInput);
378 }
379
380 SkScalar fMatrix[20];
381
382 typedef GrFragmentProcessor INHERITED;
383};
384
385GR_DEFINE_FRAGMENT_PROCESSOR_TEST(ColorMatrixEffect);
386
387const GrFragmentProcessor* ColorMatrixEffect::TestCreate(GrProcessorTestData* d) {
388 SkScalar colorMatrix[20];
389 for (size_t i = 0; i < SK_ARRAY_COUNT(colorMatrix); ++i) {
390 colorMatrix[i] = d->fRandom->nextSScalar1();
391 }
392 return ColorMatrixEffect::Create(colorMatrix);
393}
394
395const GrFragmentProcessor* SkColorMatrixFilterRowMajor255::asFragmentProcessor(GrContext*) const {
396 return ColorMatrixEffect::Create(fMatrix);
397}
398
399#endif
400
401#ifndef SK_IGNORE_TO_STRING
402void SkColorMatrixFilterRowMajor255::toString(SkString* str) const {
403 str->append("SkColorMatrixFilterRowMajor255: ");
404
405 str->append("matrix: (");
406 for (int i = 0; i < 20; ++i) {
407 str->appendScalar(fMatrix[i]);
408 if (i < 19) {
409 str->append(", ");
410 }
411 }
412 str->append(")");
413}
414#endif
415
416///////////////////////////////////////////////////////////////////////////////
417
418SkColorFilter* SkColorFilter::CreateMatrixFilterRowMajor255(const SkScalar array[20]) {
419 return new SkColorMatrixFilterRowMajor255(array);
420}
bsalomonf267c1e2016-02-01 13:16:14 -0800421
422///////////////////////////////////////////////////////////////////////////////
423
424SkColorFilter* SkColorMatrixFilterRowMajor255::CreateSingleChannelOutput(const SkScalar row[5]) {
425 SkASSERT(row);
426 SkColorMatrixFilterRowMajor255* cf = new SkColorMatrixFilterRowMajor255();
427 static_assert(sizeof(SkScalar) * 5 * 4 == sizeof(cf->fMatrix), "sizes don't match");
428 for (int i = 0; i < 4; ++i) {
429 memcpy(cf->fMatrix + 5 * i, row, sizeof(SkScalar) * 5);
430 }
431 cf->initState();
432 return cf;
433}