blob: e17f73a5611add6f058ce334c80d5e631b8f19c6 [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,
Mike Klein744908e2016-11-11 12:51:36 -0500235 SkColorSpace* dst,
236 SkFallbackAlloc* scratch,
Mike Kleineea7c162016-11-03 10:20:35 -0400237 bool shaderIsOpaque) const {
238 bool willStayOpaque = shaderIsOpaque && (fFlags & kAlphaUnchanged_Flag);
239 bool needsClamp0 = false,
240 needsClamp1 = false;
241 for (int i = 0; i < 4; i++) {
242 SkScalar min = fTranspose[i+16],
243 max = fTranspose[i+16];
244 (fTranspose[i+ 0] < 0 ? min : max) += fTranspose[i+ 0];
245 (fTranspose[i+ 4] < 0 ? min : max) += fTranspose[i+ 4];
246 (fTranspose[i+ 8] < 0 ? min : max) += fTranspose[i+ 8];
247 (fTranspose[i+12] < 0 ? min : max) += fTranspose[i+12];
248 needsClamp0 = needsClamp0 || min < 0;
249 needsClamp1 = needsClamp1 || max > 1;
250 }
251
252 if (!shaderIsOpaque) { p->append(SkRasterPipeline::unpremul); }
253 if ( true) { p->append(SkRasterPipeline::matrix_4x5, fTranspose); }
254 if (!willStayOpaque) { p->append(SkRasterPipeline::premul); }
255 if ( needsClamp0) { p->append(SkRasterPipeline::clamp_0); }
256 if ( needsClamp1) { p->append(SkRasterPipeline::clamp_a); }
257 return true;
258}
259
reedd053ce92016-03-22 10:17:23 -0700260sk_sp<SkColorFilter>
261SkColorMatrixFilterRowMajor255::makeComposed(sk_sp<SkColorFilter> innerFilter) const {
bsalomon86100022016-02-01 12:09:07 -0800262 SkScalar innerMatrix[20];
263 if (innerFilter->asColorMatrix(innerMatrix) && !needs_clamping(innerMatrix)) {
264 SkScalar concat[20];
265 set_concat(concat, fMatrix, innerMatrix);
reedd053ce92016-03-22 10:17:23 -0700266 return sk_make_sp<SkColorMatrixFilterRowMajor255>(concat);
bsalomon86100022016-02-01 12:09:07 -0800267 }
268 return nullptr;
269}
270
271#if SK_SUPPORT_GPU
272#include "GrFragmentProcessor.h"
273#include "GrInvariantOutput.h"
274#include "glsl/GrGLSLFragmentProcessor.h"
275#include "glsl/GrGLSLFragmentShaderBuilder.h"
276#include "glsl/GrGLSLProgramDataManager.h"
277#include "glsl/GrGLSLUniformHandler.h"
278
279class ColorMatrixEffect : public GrFragmentProcessor {
280public:
bungeman06ca8ec2016-06-09 08:01:03 -0700281 static sk_sp<GrFragmentProcessor> Make(const SkScalar matrix[20]) {
282 return sk_sp<GrFragmentProcessor>(new ColorMatrixEffect(matrix));
bsalomon86100022016-02-01 12:09:07 -0800283 }
284
285 const char* name() const override { return "Color Matrix"; }
286
287 GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
288
289 class GLSLProcessor : public GrGLSLFragmentProcessor {
290 public:
291 // this class always generates the same code.
Brian Salomon94efbf52016-11-29 13:43:05 -0500292 static void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder*) {}
bsalomon86100022016-02-01 12:09:07 -0800293
robertphillips9cdb9922016-02-03 12:25:40 -0800294 void emitCode(EmitArgs& args) override {
bsalomon86100022016-02-01 12:09:07 -0800295 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
cdalton5e58cee2016-02-11 12:49:47 -0800296 fMatrixHandle = uniformHandler->addUniform(kFragment_GrShaderFlag,
bsalomon86100022016-02-01 12:09:07 -0800297 kMat44f_GrSLType, kDefault_GrSLPrecision,
298 "ColorMatrix");
cdalton5e58cee2016-02-11 12:49:47 -0800299 fVectorHandle = uniformHandler->addUniform(kFragment_GrShaderFlag,
bsalomon86100022016-02-01 12:09:07 -0800300 kVec4f_GrSLType, kDefault_GrSLPrecision,
301 "ColorMatrixVector");
302
303 if (nullptr == args.fInputColor) {
304 // could optimize this case, but we aren't for now.
305 args.fInputColor = "vec4(1)";
306 }
307 GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
308 // The max() is to guard against 0 / 0 during unpremul when the incoming color is
309 // transparent black.
310 fragBuilder->codeAppendf("\tfloat nonZeroAlpha = max(%s.a, 0.00001);\n",
311 args.fInputColor);
312 fragBuilder->codeAppendf("\t%s = %s * vec4(%s.rgb / nonZeroAlpha, nonZeroAlpha) + %s;\n",
313 args.fOutputColor,
314 uniformHandler->getUniformCStr(fMatrixHandle),
315 args.fInputColor,
316 uniformHandler->getUniformCStr(fVectorHandle));
317 fragBuilder->codeAppendf("\t%s = clamp(%s, 0.0, 1.0);\n",
318 args.fOutputColor, args.fOutputColor);
319 fragBuilder->codeAppendf("\t%s.rgb *= %s.a;\n", args.fOutputColor, args.fOutputColor);
320 }
321
322 protected:
robertphillips9cdb9922016-02-03 12:25:40 -0800323 void onSetData(const GrGLSLProgramDataManager& uniManager,
324 const GrProcessor& proc) override {
bsalomon86100022016-02-01 12:09:07 -0800325 const ColorMatrixEffect& cme = proc.cast<ColorMatrixEffect>();
326 const float* m = cme.fMatrix;
327 // The GL matrix is transposed from SkColorMatrix.
328 float mt[] = {
329 m[0], m[5], m[10], m[15],
330 m[1], m[6], m[11], m[16],
331 m[2], m[7], m[12], m[17],
332 m[3], m[8], m[13], m[18],
333 };
334 static const float kScale = 1.0f / 255.0f;
335 float vec[] = {
336 m[4] * kScale, m[9] * kScale, m[14] * kScale, m[19] * kScale,
337 };
338 uniManager.setMatrix4fv(fMatrixHandle, 1, mt);
339 uniManager.set4fv(fVectorHandle, 1, vec);
340 }
341
342 private:
343 GrGLSLProgramDataManager::UniformHandle fMatrixHandle;
344 GrGLSLProgramDataManager::UniformHandle fVectorHandle;
345
346 typedef GrGLSLFragmentProcessor INHERITED;
347 };
348
349private:
350 ColorMatrixEffect(const SkScalar matrix[20]) {
351 memcpy(fMatrix, matrix, sizeof(SkScalar) * 20);
352 this->initClassID<ColorMatrixEffect>();
353 }
354
355 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
robertphillips9cdb9922016-02-03 12:25:40 -0800356 return new GLSLProcessor;
bsalomon86100022016-02-01 12:09:07 -0800357 }
358
Brian Salomon94efbf52016-11-29 13:43:05 -0500359 virtual void onGetGLSLProcessorKey(const GrShaderCaps& caps,
bsalomon86100022016-02-01 12:09:07 -0800360 GrProcessorKeyBuilder* b) const override {
361 GLSLProcessor::GenKey(*this, caps, b);
362 }
363
364 bool onIsEqual(const GrFragmentProcessor& s) const override {
365 const ColorMatrixEffect& cme = s.cast<ColorMatrixEffect>();
366 return 0 == memcmp(fMatrix, cme.fMatrix, sizeof(fMatrix));
367 }
368
369 void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
370 // We only bother to check whether the alpha channel will be constant. If SkColorMatrix had
371 // type flags it might be worth checking the other components.
372
373 // The matrix is defined such the 4th row determines the output alpha. The first four
374 // columns of that row multiply the input r, g, b, and a, respectively, and the last column
375 // is the "translation".
376 static const uint32_t kRGBAFlags[] = {
377 kR_GrColorComponentFlag,
378 kG_GrColorComponentFlag,
379 kB_GrColorComponentFlag,
380 kA_GrColorComponentFlag
381 };
382 static const int kShifts[] = {
383 GrColor_SHIFT_R, GrColor_SHIFT_G, GrColor_SHIFT_B, GrColor_SHIFT_A,
384 };
385 enum {
386 kAlphaRowStartIdx = 15,
387 kAlphaRowTranslateIdx = 19,
388 };
389
390 SkScalar outputA = 0;
391 for (int i = 0; i < 4; ++i) {
392 // If any relevant component of the color to be passed through the matrix is non-const
393 // then we can't know the final result.
394 if (0 != fMatrix[kAlphaRowStartIdx + i]) {
395 if (!(inout->validFlags() & kRGBAFlags[i])) {
396 inout->setToUnknown(GrInvariantOutput::kWill_ReadInput);
397 return;
398 } else {
399 uint32_t component = (inout->color() >> kShifts[i]) & 0xFF;
400 outputA += fMatrix[kAlphaRowStartIdx + i] * component;
401 }
402 }
403 }
404 outputA += fMatrix[kAlphaRowTranslateIdx];
405 // We pin the color to [0,1]. This would happen to the *final* color output from the frag
406 // shader but currently the effect does not pin its own output. So in the case of over/
407 // underflow this may deviate from the actual result. Maybe the effect should pin its
408 // result if the matrix could over/underflow for any component?
409 inout->setToOther(kA_GrColorComponentFlag,
410 static_cast<uint8_t>(SkScalarPin(outputA, 0, 255)) << GrColor_SHIFT_A,
411 GrInvariantOutput::kWill_ReadInput);
412 }
413
414 SkScalar fMatrix[20];
415
416 typedef GrFragmentProcessor INHERITED;
417};
418
419GR_DEFINE_FRAGMENT_PROCESSOR_TEST(ColorMatrixEffect);
420
bungeman06ca8ec2016-06-09 08:01:03 -0700421sk_sp<GrFragmentProcessor> ColorMatrixEffect::TestCreate(GrProcessorTestData* d) {
bsalomon86100022016-02-01 12:09:07 -0800422 SkScalar colorMatrix[20];
423 for (size_t i = 0; i < SK_ARRAY_COUNT(colorMatrix); ++i) {
424 colorMatrix[i] = d->fRandom->nextSScalar1();
425 }
bungeman06ca8ec2016-06-09 08:01:03 -0700426 return ColorMatrixEffect::Make(colorMatrix);
bsalomon86100022016-02-01 12:09:07 -0800427}
428
Brian Osman618d3042016-10-25 10:51:28 -0400429sk_sp<GrFragmentProcessor> SkColorMatrixFilterRowMajor255::asFragmentProcessor(
430 GrContext*, SkColorSpace*) const {
bungeman06ca8ec2016-06-09 08:01:03 -0700431 return ColorMatrixEffect::Make(fMatrix);
bsalomon86100022016-02-01 12:09:07 -0800432}
433
434#endif
435
436#ifndef SK_IGNORE_TO_STRING
437void SkColorMatrixFilterRowMajor255::toString(SkString* str) const {
438 str->append("SkColorMatrixFilterRowMajor255: ");
439
440 str->append("matrix: (");
441 for (int i = 0; i < 20; ++i) {
442 str->appendScalar(fMatrix[i]);
443 if (i < 19) {
444 str->append(", ");
445 }
446 }
447 str->append(")");
448}
449#endif
450
451///////////////////////////////////////////////////////////////////////////////
452
reedd053ce92016-03-22 10:17:23 -0700453sk_sp<SkColorFilter> SkColorFilter::MakeMatrixFilterRowMajor255(const SkScalar array[20]) {
454 return sk_sp<SkColorFilter>(new SkColorMatrixFilterRowMajor255(array));
bsalomon86100022016-02-01 12:09:07 -0800455}
bsalomonf267c1e2016-02-01 13:16:14 -0800456
457///////////////////////////////////////////////////////////////////////////////
458
reedd053ce92016-03-22 10:17:23 -0700459sk_sp<SkColorFilter>
460SkColorMatrixFilterRowMajor255::MakeSingleChannelOutput(const SkScalar row[5]) {
bsalomonf267c1e2016-02-01 13:16:14 -0800461 SkASSERT(row);
reedd053ce92016-03-22 10:17:23 -0700462 auto cf = sk_make_sp<SkColorMatrixFilterRowMajor255>();
bsalomonf267c1e2016-02-01 13:16:14 -0800463 static_assert(sizeof(SkScalar) * 5 * 4 == sizeof(cf->fMatrix), "sizes don't match");
464 for (int i = 0; i < 4; ++i) {
465 memcpy(cf->fMatrix + 5 * i, row, sizeof(SkScalar) * 5);
466 }
467 cf->initState();
468 return cf;
469}