blob: b27d40d4c7b60532b6eff1de3a84aa652b97547f [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"
reed93bb0802016-03-08 10:09:18 -080011#include "SkPM4fPriv.h"
Mike Kleineea7c162016-11-03 10:20:35 -040012#include "SkRasterPipeline.h"
bungeman06ca8ec2016-06-09 08:01:03 -070013#include "SkReadBuffer.h"
14#include "SkRefCnt.h"
15#include "SkString.h"
16#include "SkUnPreMultiply.h"
17#include "SkWriteBuffer.h"
bsalomon86100022016-02-01 12:09:07 -080018
Mike Klein1ec0dbe2016-11-03 09:47:18 -040019static void transpose_and_scale01(float dst[20], const float src[20]) {
bsalomon86100022016-02-01 12:09:07 -080020 const float* srcR = src + 0;
21 const float* srcG = src + 5;
22 const float* srcB = src + 10;
23 const float* srcA = src + 15;
24
Mike Klein1ec0dbe2016-11-03 09:47:18 -040025 for (int i = 0; i < 16; i += 4) {
reed93bb0802016-03-08 10:09:18 -080026 dst[i + 0] = *srcR++;
27 dst[i + 1] = *srcG++;
28 dst[i + 2] = *srcB++;
29 dst[i + 3] = *srcA++;
bsalomon86100022016-02-01 12:09:07 -080030 }
Mike Klein1ec0dbe2016-11-03 09:47:18 -040031 // 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);
bsalomon86100022016-02-01 12:09:07 -080036}
37
bsalomonf267c1e2016-02-01 13:16:14 -080038void SkColorMatrixFilterRowMajor255::initState() {
Mike Klein1ec0dbe2016-11-03 09:47:18 -040039 transpose_and_scale01(fTranspose, fMatrix);
bsalomon86100022016-02-01 12:09:07 -080040
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 }
bsalomon86100022016-02-01 12:09:07 -080052}
53
54///////////////////////////////////////////////////////////////////////////////
55
56SkColorMatrixFilterRowMajor255::SkColorMatrixFilterRowMajor255(const SkScalar array[20]) {
57 memcpy(fMatrix, array, 20 * sizeof(SkScalar));
bsalomonf267c1e2016-02-01 13:16:14 -080058 this->initState();
bsalomon86100022016-02-01 12:09:07 -080059}
60
61uint32_t SkColorMatrixFilterRowMajor255::getFlags() const {
62 return this->INHERITED::getFlags() | fFlags;
63}
64
65static Sk4f scale_rgb(float scale) {
66 static_assert(SkPM4f::A == 3, "Alpha is lane 3");
67 return Sk4f(scale, scale, scale, 1);
68}
69
70static Sk4f premul(const Sk4f& x) {
mtklein7c249e52016-02-21 10:54:19 -080071 return x * scale_rgb(x[SkPM4f::A]);
bsalomon86100022016-02-01 12:09:07 -080072}
73
74static Sk4f unpremul(const Sk4f& x) {
mtklein7c249e52016-02-21 10:54:19 -080075 return x * scale_rgb(1 / x[SkPM4f::A]); // TODO: fast/approx invert?
bsalomon86100022016-02-01 12:09:07 -080076}
77
78static Sk4f clamp_0_1(const Sk4f& x) {
79 return Sk4f::Max(Sk4f::Min(x, Sk4f(1)), Sk4f(0));
80}
81
82static SkPMColor round(const Sk4f& x) {
83 SkPMColor c;
84 SkNx_cast<uint8_t>(x * Sk4f(255) + Sk4f(0.5f)).store(&c);
85 return c;
86}
87
88template <typename Adaptor, typename T>
89void filter_span(const float array[], const T src[], int count, T dst[]) {
bsalomon86100022016-02-01 12:09:07 -080090 const Sk4f c0 = Sk4f::Load(array + 0);
91 const Sk4f c1 = Sk4f::Load(array + 4);
92 const Sk4f c2 = Sk4f::Load(array + 8);
93 const Sk4f c3 = Sk4f::Load(array + 12);
Mike Klein1ec0dbe2016-11-03 09:47:18 -040094 const Sk4f c4 = Sk4f::Load(array + 16);
bsalomon86100022016-02-01 12:09:07 -080095
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]);
mtklein7c249e52016-02-21 10:54:19 -0800101 float srcA = srcf[SkPM4f::A];
bsalomon86100022016-02-01 12:09:07 -0800102
103 if (0 == srcA) {
104 dst[i] = matrix_translate_pmcolor;
105 continue;
106 }
107 if (1 != srcA) {
108 srcf = unpremul(srcf);
109 }
110
reed93bb0802016-03-08 10:09:18 -0800111 Sk4f r4 = srcf[Adaptor::R];
112 Sk4f g4 = srcf[Adaptor::G];
113 Sk4f b4 = srcf[Adaptor::B];
114 Sk4f a4 = srcf[Adaptor::A];
bsalomon86100022016-02-01 12:09:07 -0800115 // apply matrix
116 Sk4f dst4 = c0 * r4 + c1 * g4 + c2 * b4 + c3 * a4 + c4;
117
118 dst[i] = Adaptor::From4f(premul(clamp_0_1(dst4)));
119 }
120}
121
122struct SkPMColorAdaptor {
reed93bb0802016-03-08 10:09:18 -0800123 enum {
124 R = SK_R_INDEX,
125 G = SK_G_INDEX,
126 B = SK_B_INDEX,
127 A = SK_A_INDEX,
128 };
bsalomon86100022016-02-01 12:09:07 -0800129 static SkPMColor From4f(const Sk4f& c4) {
reed93bb0802016-03-08 10:09:18 -0800130 return round(swizzle_rb_if_bgra(c4));
bsalomon86100022016-02-01 12:09:07 -0800131 }
132 static Sk4f To4f(SkPMColor c) {
mtklein0c902472016-07-20 18:10:07 -0700133 return Sk4f_fromL32(c);
bsalomon86100022016-02-01 12:09:07 -0800134 }
135};
136void SkColorMatrixFilterRowMajor255::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) const {
137 filter_span<SkPMColorAdaptor>(fTranspose, src, count, dst);
138}
139
140struct SkPM4fAdaptor {
reed93bb0802016-03-08 10:09:18 -0800141 enum {
142 R = SkPM4f::R,
143 G = SkPM4f::G,
144 B = SkPM4f::B,
145 A = SkPM4f::A,
146 };
bsalomon86100022016-02-01 12:09:07 -0800147 static SkPM4f From4f(const Sk4f& c4) {
reed93bb0802016-03-08 10:09:18 -0800148 return SkPM4f::From4f(c4);
bsalomon86100022016-02-01 12:09:07 -0800149 }
150 static Sk4f To4f(const SkPM4f& c) {
reed93bb0802016-03-08 10:09:18 -0800151 return c.to4f();
bsalomon86100022016-02-01 12:09:07 -0800152 }
153};
154void SkColorMatrixFilterRowMajor255::filterSpan4f(const SkPM4f src[], int count, SkPM4f dst[]) const {
155 filter_span<SkPM4fAdaptor>(fTranspose, src, count, dst);
156}
157
158///////////////////////////////////////////////////////////////////////////////
159
160void SkColorMatrixFilterRowMajor255::flatten(SkWriteBuffer& buffer) const {
161 SkASSERT(sizeof(fMatrix)/sizeof(SkScalar) == 20);
162 buffer.writeScalarArray(fMatrix, 20);
163}
164
reed60c9b582016-04-03 09:11:13 -0700165sk_sp<SkFlattenable> SkColorMatrixFilterRowMajor255::CreateProc(SkReadBuffer& buffer) {
bsalomon86100022016-02-01 12:09:07 -0800166 SkScalar matrix[20];
167 if (buffer.readScalarArray(matrix, 20)) {
reed60c9b582016-04-03 09:11:13 -0700168 return sk_make_sp<SkColorMatrixFilterRowMajor255>(matrix);
bsalomon86100022016-02-01 12:09:07 -0800169 }
170 return nullptr;
171}
172
173bool SkColorMatrixFilterRowMajor255::asColorMatrix(SkScalar matrix[20]) const {
174 if (matrix) {
175 memcpy(matrix, fMatrix, 20 * sizeof(SkScalar));
176 }
177 return true;
178}
179
180///////////////////////////////////////////////////////////////////////////////
181// This code was duplicated from src/effects/SkColorMatrixc.cpp in order to be used in core.
182//////
183
184// To detect if we need to apply clamping after applying a matrix, we check if
185// any output component might go outside of [0, 255] for any combination of
186// input components in [0..255].
187// Each output component is an affine transformation of the input component, so
188// the minimum and maximum values are for any combination of minimum or maximum
189// values of input components (i.e. 0 or 255).
190// E.g. if R' = x*R + y*G + z*B + w*A + t
191// Then the maximum value will be for R=255 if x>0 or R=0 if x<0, and the
192// minimum value will be for R=0 if x>0 or R=255 if x<0.
193// Same goes for all components.
194static bool component_needs_clamping(const SkScalar row[5]) {
195 SkScalar maxValue = row[4] / 255;
196 SkScalar minValue = row[4] / 255;
197 for (int i = 0; i < 4; ++i) {
198 if (row[i] > 0)
199 maxValue += row[i];
200 else
201 minValue += row[i];
202 }
203 return (maxValue > 1) || (minValue < 0);
204}
205
206static bool needs_clamping(const SkScalar matrix[20]) {
207 return component_needs_clamping(matrix)
208 || component_needs_clamping(matrix+5)
209 || component_needs_clamping(matrix+10)
210 || component_needs_clamping(matrix+15);
211}
212
213static void set_concat(SkScalar result[20], const SkScalar outer[20], const SkScalar inner[20]) {
214 int index = 0;
215 for (int j = 0; j < 20; j += 5) {
216 for (int i = 0; i < 4; i++) {
217 result[index++] = outer[j + 0] * inner[i + 0] +
218 outer[j + 1] * inner[i + 5] +
219 outer[j + 2] * inner[i + 10] +
220 outer[j + 3] * inner[i + 15];
221 }
222 result[index++] = outer[j + 0] * inner[4] +
223 outer[j + 1] * inner[9] +
224 outer[j + 2] * inner[14] +
225 outer[j + 3] * inner[19] +
226 outer[j + 4];
227 }
228}
229
230///////////////////////////////////////////////////////////////////////////////
231// End duplication
232//////
233
Mike Kleineea7c162016-11-03 10:20:35 -0400234bool SkColorMatrixFilterRowMajor255::onAppendStages(SkRasterPipeline* p,
235 bool shaderIsOpaque) const {
236 bool willStayOpaque = shaderIsOpaque && (fFlags & kAlphaUnchanged_Flag);
237 bool needsClamp0 = false,
238 needsClamp1 = false;
239 for (int i = 0; i < 4; i++) {
240 SkScalar min = fTranspose[i+16],
241 max = fTranspose[i+16];
242 (fTranspose[i+ 0] < 0 ? min : max) += fTranspose[i+ 0];
243 (fTranspose[i+ 4] < 0 ? min : max) += fTranspose[i+ 4];
244 (fTranspose[i+ 8] < 0 ? min : max) += fTranspose[i+ 8];
245 (fTranspose[i+12] < 0 ? min : max) += fTranspose[i+12];
246 needsClamp0 = needsClamp0 || min < 0;
247 needsClamp1 = needsClamp1 || max > 1;
248 }
249
250 if (!shaderIsOpaque) { p->append(SkRasterPipeline::unpremul); }
251 if ( true) { p->append(SkRasterPipeline::matrix_4x5, fTranspose); }
252 if (!willStayOpaque) { p->append(SkRasterPipeline::premul); }
253 if ( needsClamp0) { p->append(SkRasterPipeline::clamp_0); }
254 if ( needsClamp1) { p->append(SkRasterPipeline::clamp_a); }
255 return true;
256}
257
reedd053ce92016-03-22 10:17:23 -0700258sk_sp<SkColorFilter>
259SkColorMatrixFilterRowMajor255::makeComposed(sk_sp<SkColorFilter> innerFilter) const {
bsalomon86100022016-02-01 12:09:07 -0800260 SkScalar innerMatrix[20];
261 if (innerFilter->asColorMatrix(innerMatrix) && !needs_clamping(innerMatrix)) {
262 SkScalar concat[20];
263 set_concat(concat, fMatrix, innerMatrix);
reedd053ce92016-03-22 10:17:23 -0700264 return sk_make_sp<SkColorMatrixFilterRowMajor255>(concat);
bsalomon86100022016-02-01 12:09:07 -0800265 }
266 return nullptr;
267}
268
269#if SK_SUPPORT_GPU
270#include "GrFragmentProcessor.h"
271#include "GrInvariantOutput.h"
272#include "glsl/GrGLSLFragmentProcessor.h"
273#include "glsl/GrGLSLFragmentShaderBuilder.h"
274#include "glsl/GrGLSLProgramDataManager.h"
275#include "glsl/GrGLSLUniformHandler.h"
276
277class ColorMatrixEffect : public GrFragmentProcessor {
278public:
bungeman06ca8ec2016-06-09 08:01:03 -0700279 static sk_sp<GrFragmentProcessor> Make(const SkScalar matrix[20]) {
280 return sk_sp<GrFragmentProcessor>(new ColorMatrixEffect(matrix));
bsalomon86100022016-02-01 12:09:07 -0800281 }
282
283 const char* name() const override { return "Color Matrix"; }
284
285 GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
286
287 class GLSLProcessor : public GrGLSLFragmentProcessor {
288 public:
289 // this class always generates the same code.
robertphillips9cdb9922016-02-03 12:25:40 -0800290 static void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder*) {}
bsalomon86100022016-02-01 12:09:07 -0800291
robertphillips9cdb9922016-02-03 12:25:40 -0800292 void emitCode(EmitArgs& args) override {
bsalomon86100022016-02-01 12:09:07 -0800293 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
cdalton5e58cee2016-02-11 12:49:47 -0800294 fMatrixHandle = uniformHandler->addUniform(kFragment_GrShaderFlag,
bsalomon86100022016-02-01 12:09:07 -0800295 kMat44f_GrSLType, kDefault_GrSLPrecision,
296 "ColorMatrix");
cdalton5e58cee2016-02-11 12:49:47 -0800297 fVectorHandle = uniformHandler->addUniform(kFragment_GrShaderFlag,
bsalomon86100022016-02-01 12:09:07 -0800298 kVec4f_GrSLType, kDefault_GrSLPrecision,
299 "ColorMatrixVector");
300
301 if (nullptr == args.fInputColor) {
302 // could optimize this case, but we aren't for now.
303 args.fInputColor = "vec4(1)";
304 }
305 GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
306 // The max() is to guard against 0 / 0 during unpremul when the incoming color is
307 // transparent black.
308 fragBuilder->codeAppendf("\tfloat nonZeroAlpha = max(%s.a, 0.00001);\n",
309 args.fInputColor);
310 fragBuilder->codeAppendf("\t%s = %s * vec4(%s.rgb / nonZeroAlpha, nonZeroAlpha) + %s;\n",
311 args.fOutputColor,
312 uniformHandler->getUniformCStr(fMatrixHandle),
313 args.fInputColor,
314 uniformHandler->getUniformCStr(fVectorHandle));
315 fragBuilder->codeAppendf("\t%s = clamp(%s, 0.0, 1.0);\n",
316 args.fOutputColor, args.fOutputColor);
317 fragBuilder->codeAppendf("\t%s.rgb *= %s.a;\n", args.fOutputColor, args.fOutputColor);
318 }
319
320 protected:
robertphillips9cdb9922016-02-03 12:25:40 -0800321 void onSetData(const GrGLSLProgramDataManager& uniManager,
322 const GrProcessor& proc) override {
bsalomon86100022016-02-01 12:09:07 -0800323 const ColorMatrixEffect& cme = proc.cast<ColorMatrixEffect>();
324 const float* m = cme.fMatrix;
325 // The GL matrix is transposed from SkColorMatrix.
326 float mt[] = {
327 m[0], m[5], m[10], m[15],
328 m[1], m[6], m[11], m[16],
329 m[2], m[7], m[12], m[17],
330 m[3], m[8], m[13], m[18],
331 };
332 static const float kScale = 1.0f / 255.0f;
333 float vec[] = {
334 m[4] * kScale, m[9] * kScale, m[14] * kScale, m[19] * kScale,
335 };
336 uniManager.setMatrix4fv(fMatrixHandle, 1, mt);
337 uniManager.set4fv(fVectorHandle, 1, vec);
338 }
339
340 private:
341 GrGLSLProgramDataManager::UniformHandle fMatrixHandle;
342 GrGLSLProgramDataManager::UniformHandle fVectorHandle;
343
344 typedef GrGLSLFragmentProcessor INHERITED;
345 };
346
347private:
348 ColorMatrixEffect(const SkScalar matrix[20]) {
349 memcpy(fMatrix, matrix, sizeof(SkScalar) * 20);
350 this->initClassID<ColorMatrixEffect>();
351 }
352
353 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
robertphillips9cdb9922016-02-03 12:25:40 -0800354 return new GLSLProcessor;
bsalomon86100022016-02-01 12:09:07 -0800355 }
356
357 virtual void onGetGLSLProcessorKey(const GrGLSLCaps& caps,
358 GrProcessorKeyBuilder* b) const override {
359 GLSLProcessor::GenKey(*this, caps, b);
360 }
361
362 bool onIsEqual(const GrFragmentProcessor& s) const override {
363 const ColorMatrixEffect& cme = s.cast<ColorMatrixEffect>();
364 return 0 == memcmp(fMatrix, cme.fMatrix, sizeof(fMatrix));
365 }
366
367 void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
368 // We only bother to check whether the alpha channel will be constant. If SkColorMatrix had
369 // type flags it might be worth checking the other components.
370
371 // The matrix is defined such the 4th row determines the output alpha. The first four
372 // columns of that row multiply the input r, g, b, and a, respectively, and the last column
373 // is the "translation".
374 static const uint32_t kRGBAFlags[] = {
375 kR_GrColorComponentFlag,
376 kG_GrColorComponentFlag,
377 kB_GrColorComponentFlag,
378 kA_GrColorComponentFlag
379 };
380 static const int kShifts[] = {
381 GrColor_SHIFT_R, GrColor_SHIFT_G, GrColor_SHIFT_B, GrColor_SHIFT_A,
382 };
383 enum {
384 kAlphaRowStartIdx = 15,
385 kAlphaRowTranslateIdx = 19,
386 };
387
388 SkScalar outputA = 0;
389 for (int i = 0; i < 4; ++i) {
390 // If any relevant component of the color to be passed through the matrix is non-const
391 // then we can't know the final result.
392 if (0 != fMatrix[kAlphaRowStartIdx + i]) {
393 if (!(inout->validFlags() & kRGBAFlags[i])) {
394 inout->setToUnknown(GrInvariantOutput::kWill_ReadInput);
395 return;
396 } else {
397 uint32_t component = (inout->color() >> kShifts[i]) & 0xFF;
398 outputA += fMatrix[kAlphaRowStartIdx + i] * component;
399 }
400 }
401 }
402 outputA += fMatrix[kAlphaRowTranslateIdx];
403 // We pin the color to [0,1]. This would happen to the *final* color output from the frag
404 // shader but currently the effect does not pin its own output. So in the case of over/
405 // underflow this may deviate from the actual result. Maybe the effect should pin its
406 // result if the matrix could over/underflow for any component?
407 inout->setToOther(kA_GrColorComponentFlag,
408 static_cast<uint8_t>(SkScalarPin(outputA, 0, 255)) << GrColor_SHIFT_A,
409 GrInvariantOutput::kWill_ReadInput);
410 }
411
412 SkScalar fMatrix[20];
413
414 typedef GrFragmentProcessor INHERITED;
415};
416
417GR_DEFINE_FRAGMENT_PROCESSOR_TEST(ColorMatrixEffect);
418
bungeman06ca8ec2016-06-09 08:01:03 -0700419sk_sp<GrFragmentProcessor> ColorMatrixEffect::TestCreate(GrProcessorTestData* d) {
bsalomon86100022016-02-01 12:09:07 -0800420 SkScalar colorMatrix[20];
421 for (size_t i = 0; i < SK_ARRAY_COUNT(colorMatrix); ++i) {
422 colorMatrix[i] = d->fRandom->nextSScalar1();
423 }
bungeman06ca8ec2016-06-09 08:01:03 -0700424 return ColorMatrixEffect::Make(colorMatrix);
bsalomon86100022016-02-01 12:09:07 -0800425}
426
Brian Osman618d3042016-10-25 10:51:28 -0400427sk_sp<GrFragmentProcessor> SkColorMatrixFilterRowMajor255::asFragmentProcessor(
428 GrContext*, SkColorSpace*) const {
bungeman06ca8ec2016-06-09 08:01:03 -0700429 return ColorMatrixEffect::Make(fMatrix);
bsalomon86100022016-02-01 12:09:07 -0800430}
431
432#endif
433
434#ifndef SK_IGNORE_TO_STRING
435void SkColorMatrixFilterRowMajor255::toString(SkString* str) const {
436 str->append("SkColorMatrixFilterRowMajor255: ");
437
438 str->append("matrix: (");
439 for (int i = 0; i < 20; ++i) {
440 str->appendScalar(fMatrix[i]);
441 if (i < 19) {
442 str->append(", ");
443 }
444 }
445 str->append(")");
446}
447#endif
448
449///////////////////////////////////////////////////////////////////////////////
450
reedd053ce92016-03-22 10:17:23 -0700451sk_sp<SkColorFilter> SkColorFilter::MakeMatrixFilterRowMajor255(const SkScalar array[20]) {
452 return sk_sp<SkColorFilter>(new SkColorMatrixFilterRowMajor255(array));
bsalomon86100022016-02-01 12:09:07 -0800453}
bsalomonf267c1e2016-02-01 13:16:14 -0800454
455///////////////////////////////////////////////////////////////////////////////
456
reedd053ce92016-03-22 10:17:23 -0700457sk_sp<SkColorFilter>
458SkColorMatrixFilterRowMajor255::MakeSingleChannelOutput(const SkScalar row[5]) {
bsalomonf267c1e2016-02-01 13:16:14 -0800459 SkASSERT(row);
reedd053ce92016-03-22 10:17:23 -0700460 auto cf = sk_make_sp<SkColorMatrixFilterRowMajor255>();
bsalomonf267c1e2016-02-01 13:16:14 -0800461 static_assert(sizeof(SkScalar) * 5 * 4 == sizeof(cf->fMatrix), "sizes don't match");
462 for (int i = 0; i < 4; ++i) {
463 memcpy(cf->fMatrix + 5 * i, row, sizeof(SkScalar) * 5);
464 }
465 cf->initState();
466 return cf;
467}