Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(332)

Side by Side Diff: src/gpu/effects/GrDashingEffect.cpp

Issue 274673004: Add Dashing gpu effect for simple dashed lines (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: Move DrawDashLine into namespace Created 6 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « src/gpu/effects/GrDashingEffect.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /*
2 * Copyright 2014 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 "GrDashingEffect.h"
9
10 #include "gl/GrGLEffect.h"
11 #include "gl/GrGLSL.h"
12 #include "GrContext.h"
13 #include "GrCoordTransform.h"
14 #include "GrDrawTargetCaps.h"
15 #include "GrEffect.h"
16 #include "GrTBackendEffectFactory.h"
17 #include "SkGpuDevice.h"
18 #include "SkGr.h"
19
20 ///////////////////////////////////////////////////////////////////////////////
21
22 static void calc_dash_scaling(SkScalar* parallelScale, SkScalar* perpScale,
23 const SkMatrix& viewMatrix, const SkPoint pts[2]) {
24 SkVector vecSrc = pts[1] - pts[0];
25 SkScalar magSrc = vecSrc.length();
26 SkScalar invSrc = magSrc ? SkScalarInvert(magSrc) : 0;
27 vecSrc.scale(invSrc);
28
29 SkVector vecSrcPerp;
30 vecSrc.rotateCW(&vecSrcPerp);
31 viewMatrix.mapVectors(&vecSrc, 1);
32 viewMatrix.mapVectors(&vecSrcPerp, 1);
33
34 // parallelScale tells how much to scale along the line parallel to the dash line
35 // perpScale tells how much to scale in the direction perpendicular to the d ash line
36 *parallelScale = vecSrc.length();
37 *perpScale = vecSrcPerp.length();
38 }
39
40 // calculates the rotation needed to aligned pts to the x axis with pts[0] < pts [1]
41 // Stores the rotation matrix in rotMatrix, and the mapped points in ptsRot
42 static void align_to_x_axis(const SkPoint pts[2], SkMatrix* rotMatrix, SkPoint p tsRot[2] = NULL) {
43 SkVector vec = pts[1] - pts[0];
44 SkScalar mag = vec.length();
45 SkScalar inv = mag ? SkScalarInvert(mag) : 0;
46
47 vec.scale(inv);
48 rotMatrix->setSinCos(-vec.fY, vec.fX, pts[0].fX, pts[0].fY);
49 if (ptsRot) {
50 rotMatrix->mapPoints(ptsRot, pts, 2);
51 // correction for numerical issues if map doesn't make ptsRot exactly ho rizontal
52 ptsRot[1].fY = pts[0].fY;
53 }
54 }
55
56 // Assumes phase < sum of all intervals
57 static SkScalar calc_start_adjustment(const SkPathEffect::DashInfo& info) {
58 SkASSERT(info.fPhase < info.fIntervals[0] + info.fIntervals[1]);
59 if (info.fPhase >= info.fIntervals[0] && info.fPhase != 0) {
60 SkScalar srcIntervalLen = info.fIntervals[0] + info.fIntervals[1];
61 return srcIntervalLen - info.fPhase;
62 }
63 return 0;
64 }
65
66 static SkScalar calc_end_adjustment(const SkPathEffect::DashInfo& info, const Sk Point pts[2], SkScalar* endingInt) {
67 if (pts[1].fX <= pts[0].fX) {
68 return 0;
69 }
70 SkScalar srcIntervalLen = info.fIntervals[0] + info.fIntervals[1];
71 SkScalar totalLen = pts[1].fX - pts[0].fX;
72 SkScalar temp = SkScalarDiv(totalLen, srcIntervalLen);
73 SkScalar numFullIntervals = SkScalarFloorToScalar(temp);
74 *endingInt = totalLen - numFullIntervals * srcIntervalLen + info.fPhase;
75 temp = SkScalarDiv(*endingInt, srcIntervalLen);
76 *endingInt = *endingInt - SkScalarFloorToScalar(temp) * srcIntervalLen;
77 if (0 == *endingInt) {
78 *endingInt = srcIntervalLen;
79 }
80 if (*endingInt > info.fIntervals[0]) {
81 if (0 == info.fIntervals[0]) {
82 *endingInt -= 0.01; // make sure we capture the last zero size pnt ( used if has caps)
83 }
84 return *endingInt - info.fIntervals[0];
85 }
86 return 0;
87 }
88
89
90 bool GrDashingEffect::DrawDashLine(const SkPoint pts[2], const SkPaint& paint, S kGpuDevice* dev) {
91 GrContext* context = dev->context();
92 if (context->getRenderTarget()->isMultisampled()) {
93 return false;
94 }
95
96 const SkMatrix& viewMatrix = context->getMatrix();
97 if (!viewMatrix.preservesRightAngles()) {
98 return false;
99 }
100
101 const SkPathEffect* pe = paint.getPathEffect();
102 SkPathEffect::DashInfo info;
103 SkPathEffect::DashType dashType = pe->asADash(&info);
104 // Must be a dash effect with 2 intervals (1 on and 1 off)
105 if (SkPathEffect::kDash_DashType != dashType || 2 != info.fCount) {
106 return false;
107 }
108
109 SkPaint::Cap cap = paint.getStrokeCap();
110 // Current we do don't handle Round or Square cap dashes
111 if (SkPaint::kRound_Cap == cap) {
112 return false;
113 }
114
115 SkScalar srcStrokeWidth = paint.getStrokeWidth();
116
117 // Get all info about the dash effect
118 SkAutoTArray<SkScalar> intervals(info.fCount);
119 info.fIntervals = intervals.get();
120 pe->asADash(&info);
121
122 // the phase should be normalized to be [0, sum of all intervals)
123 SkASSERT(info.fPhase >= 0 && info.fPhase < info.fIntervals[0] + info.fInterv als[1]);
124
125 SkMatrix coordTrans;
126
127 // Rotate the src pts so they are aligned horizontally with pts[0].fX < pts[ 1].fX
128 SkMatrix srcRotInv;
129 SkPoint ptsRot[2];
130 if (pts[0].fY != pts[1].fY || pts[0].fX > pts[1].fX) {
131 align_to_x_axis(pts, &coordTrans, ptsRot);
132 if(!coordTrans.invert(&srcRotInv)) {
133 return false;
134 }
135 } else {
136 coordTrans.reset();
137 srcRotInv.reset();
138 memcpy(ptsRot, pts, 2 * sizeof(SkPoint));
139 }
140
141 GrPaint grPaint;
142 SkPaint2GrPaintShader(dev, paint, true, &grPaint);
143
144 bool useAA = paint.isAntiAlias();
145
146 // Scale corrections of intervals and stroke from view matrix
147 SkScalar parallelScale;
148 SkScalar perpScale;
149 calc_dash_scaling(&parallelScale, &perpScale, viewMatrix, ptsRot);
150
151 bool hasCap = SkPaint::kSquare_Cap == cap && 0 != srcStrokeWidth;
152
153 // We always want to at least stroke out half a pixel on each side in device space
154 // so 0.5f / perpScale gives us this min in src space
155 SkScalar halfStroke = SkMaxScalar(srcStrokeWidth * 0.5f, 0.5f / perpScale);
156
157 SkScalar xStroke;
158 if (!hasCap) {
159 xStroke = 0.f;
160 } else {
161 xStroke = halfStroke;
162 }
163
164 // If we are using AA, check to see if we are drawing a partial dash at the start. If so
165 // draw it separately here and adjust our start point accordingly
166 if (useAA) {
167 if (info.fPhase > 0 && info.fPhase < info.fIntervals[0]) {
168 SkPoint startPts[2];
169 startPts[0] = ptsRot[0];
170 startPts[1].fY = startPts[0].fY;
171 startPts[1].fX = SkMinScalar(startPts[0].fX + info.fIntervals[0] - i nfo.fPhase,
172 ptsRot[1].fX);
173 SkRect startRect;
174 startRect.set(startPts, 2);
175 startRect.outset(xStroke, halfStroke);
176 context->drawRect(grPaint, startRect, NULL, &srcRotInv);
177
178 ptsRot[0].fX += info.fIntervals[0] + info.fIntervals[1] - info.fPhas e;
179 info.fPhase = 0;
180 }
181 }
182
183 // adjustments for start and end of bounding rect so we only draw dash inter vals
184 // contained in the original line segment.
185 SkScalar startAdj = calc_start_adjustment(info);
186 SkScalar endingInterval = 0;
187 SkScalar endAdj = calc_end_adjustment(info, ptsRot, &endingInterval);
188 if (ptsRot[0].fX + startAdj >= ptsRot[1].fX - endAdj) {
189 // Nothing left to draw so just return
190 return true;
191 }
192
193 // If we are using AA, check to see if we are drawing a partial dash at then end. If so
194 // draw it separately here and adjust our end point accordingly
195 if (useAA) {
196 // If we adjusted the end then we will not be drawing a partial dash at the end.
197 // If we didn't adjust the end point then we just need to make sure the ending
198 // dash isn't a full dash
199 if (0 == endAdj && endingInterval != info.fIntervals[0]) {
200
201 SkPoint endPts[2];
202 endPts[1] = ptsRot[1];
203 endPts[0].fY = endPts[1].fY;
204 endPts[0].fX = endPts[1].fX - endingInterval;
205
206 SkRect endRect;
207 endRect.set(endPts, 2);
208 endRect.outset(xStroke, halfStroke);
209 context->drawRect(grPaint, endRect, NULL, &srcRotInv);
210
211 ptsRot[1].fX -= endingInterval + info.fIntervals[1];
212 if (ptsRot[0].fX >= ptsRot[1].fX) {
213 // Nothing left to draw so just return
214 return true;
215 }
216 }
217 }
218 coordTrans.postConcat(viewMatrix);
219
220 SkPoint devicePts[2];
221 viewMatrix.mapPoints(devicePts, ptsRot, 2);
222
223 info.fIntervals[0] *= parallelScale;
224 info.fIntervals[1] *= parallelScale;
225 info.fPhase *= parallelScale;
226 SkScalar strokeWidth = srcStrokeWidth * perpScale;
227
228 if ((strokeWidth < 1.f && !useAA) || 0.f == strokeWidth) {
229 strokeWidth = 1.f;
230 }
231
232 // Set up coordTransform for device space transforms
233 // We rotate the dashed line such that it is horizontal with the start point at smaller x
234 // then we translate the start point to the origin
235 if (devicePts[0].fY != devicePts[1].fY || devicePts[0].fX > devicePts[1].fX) {
236 SkMatrix rot;
237 align_to_x_axis(devicePts, &rot);
238 coordTrans.postConcat(rot);
239 }
240 coordTrans.postTranslate(-devicePts[0].fX, -devicePts[0].fY);
241 coordTrans.postTranslate(info.fIntervals[1] * 0.5f + info.fPhase, 0);
242
243 if (SkPaint::kSquare_Cap == cap && 0 != srcStrokeWidth) {
244 // add cap to on interveal and remove from off interval
245 info.fIntervals[0] += strokeWidth;
246 info.fIntervals[1] -= strokeWidth;
247 }
248
249 if (info.fIntervals[1] > 0.f) {
250 GrEffectEdgeType edgeType= useAA ? kFillAA_GrEffectEdgeType :
251 kFillBW_GrEffectEdgeType;
252 grPaint.addCoverageEffect(
253 GrDashingEffect::Create(edgeType, info, coordTrans, strokeWidth))->u nref();
254 grPaint.setAntiAlias(false);
255 }
256
257 SkRect rect;
258 bool bloat = useAA && info.fIntervals[1] > 0.f;
259 SkScalar bloatX = bloat ? 0.5f / parallelScale : 0.f;
260 SkScalar bloatY = bloat ? 0.5f / perpScale : 0.f;
261 ptsRot[0].fX += startAdj;
262 ptsRot[1].fX -= endAdj;
263 if (!hasCap) {
264 xStroke = 0.f;
265 } else {
266 xStroke = halfStroke;
267 }
268 rect.set(ptsRot, 2);
269 rect.outset(bloatX + xStroke, bloatY + halfStroke);
270 context->drawRect(grPaint, rect, NULL, &srcRotInv);
271
272 return true;
273 }
274
275 //////////////////////////////////////////////////////////////////////////////
276
277 class GLDashingLineEffect;
278
279 class DashingLineEffect : public GrEffect {
280 public:
281 typedef SkPathEffect::DashInfo DashInfo;
282
283 /**
284 * The effect calculates the coverage for the case of a horizontal line in d evice space.
285 * The matrix that is passed in should be able to convert a line in source s pace to a
286 * horizontal line in device space. Additionally, the coord transform matrix should translate
287 * the the start of line to origin, and the shift it along the positive x-ax is by the phase
288 * and half the off interval.
289 */
290 static GrEffectRef* Create(GrEffectEdgeType edgeType, const DashInfo& info,
291 const SkMatrix& matrix, SkScalar strokeWidth);
292
293 virtual ~DashingLineEffect();
294
295 static const char* Name() { return "DashingEffect"; }
296
297 GrEffectEdgeType getEdgeType() const { return fEdgeType; }
298
299 const SkRect& getRect() const { return fRect; }
300
301 SkScalar getIntervalLength() const { return fIntervalLength; }
302
303 typedef GLDashingLineEffect GLEffect;
304
305 virtual void getConstantColorComponents(GrColor* color, uint32_t* validFlags ) const SK_OVERRIDE;
306
307 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE;
308
309 private:
310 DashingLineEffect(GrEffectEdgeType edgeType, const DashInfo& info, const SkM atrix& matrix,
311 SkScalar strokeWidth);
312
313 virtual bool onIsEqual(const GrEffect& other) const SK_OVERRIDE;
314
315 GrEffectEdgeType fEdgeType;
316 GrCoordTransform fCoordTransform;
317 SkRect fRect;
318 SkScalar fIntervalLength;
319
320 GR_DECLARE_EFFECT_TEST;
321
322 typedef GrEffect INHERITED;
323 };
324
325 //////////////////////////////////////////////////////////////////////////////
326
327 class GLDashingLineEffect : public GrGLEffect {
328 public:
329 GLDashingLineEffect(const GrBackendEffectFactory&, const GrDrawEffect&);
330
331 virtual void emitCode(GrGLShaderBuilder* builder,
332 const GrDrawEffect& drawEffect,
333 EffectKey key,
334 const char* outputColor,
335 const char* inputColor,
336 const TransformedCoordsArray&,
337 const TextureSamplerArray&) SK_OVERRIDE;
338
339 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
340
341 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVER RIDE;
342
343 private:
344 GrGLUniformManager::UniformHandle fRectUniform;
345 GrGLUniformManager::UniformHandle fIntervalUniform;
346 SkRect fPrevRect;
347 SkScalar fPrevIntervalLength;
348 typedef GrGLEffect INHERITED;
349 };
350
351 GLDashingLineEffect::GLDashingLineEffect(const GrBackendEffectFactory& factory,
352 const GrDrawEffect& drawEffect)
353 : INHERITED (factory) {
354 fPrevRect.fLeft = SK_ScalarNaN;
355 fPrevIntervalLength = SK_ScalarMax;
356
357 }
358
359 void GLDashingLineEffect::emitCode(GrGLShaderBuilder* builder,
360 const GrDrawEffect& drawEffect,
361 EffectKey key,
362 const char* outputColor,
363 const char* inputColor,
364 const TransformedCoordsArray& coords,
365 const TextureSamplerArray& samplers) {
366 const DashingLineEffect& de = drawEffect.castEffect<DashingLineEffect>();
367 const char *rectName;
368 // The rect uniform's xyzw refer to (left + 0.5, top + 0.5, right - 0.5, bot tom - 0.5),
369 // respectively.
370 fRectUniform = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
371 kVec4f_GrSLType,
372 "rect",
373 &rectName);
374 const char *intervalName;
375 // The interval uniform's refers to the total length of the interval (on + o ff)
376 fIntervalUniform = builder->addUniform(GrGLShaderBuilder::kFragment_Visibili ty,
377 kFloat_GrSLType,
378 "interval",
379 &intervalName);
380 // transforms all points so that we can compare them to our test rect
381 builder->fsCodeAppendf("\t\tfloat xShifted = %s.x - floor(%s.x / %s) * %s;\n ",
382 coords[0].c_str(), coords[0].c_str(), intervalName, i ntervalName);
383 builder->fsCodeAppendf("\t\tvec2 fragPosShifted = vec2(xShifted, %s.y);\n", coords[0].c_str());
384 if (GrEffectEdgeTypeIsAA(de.getEdgeType())) {
385 // The amount of coverage removed in x and y by the edges is computed as a pair of negative
386 // numbers, xSub and ySub.
387 builder->fsCodeAppend("\t\tfloat xSub, ySub;\n");
388 builder->fsCodeAppendf("\t\txSub = min(fragPosShifted.x - %s.x, 0.0);\n" , rectName);
389 builder->fsCodeAppendf("\t\txSub += min(%s.z - fragPosShifted.x, 0.0);\n ", rectName);
390 builder->fsCodeAppendf("\t\tySub = min(fragPosShifted.y - %s.y, 0.0);\n" , rectName);
391 builder->fsCodeAppendf("\t\tySub += min(%s.w - fragPosShifted.y, 0.0);\n ", rectName);
392 // Now compute coverage in x and y and multiply them to get the fraction of the pixel
393 // covered.
394 builder->fsCodeAppendf("\t\tfloat alpha = (1.0 + max(xSub, -1.0)) * (1.0 + max(ySub, -1.0));\n");
395 } else {
396 // Assuming the bounding geometry is tight so no need to check y values
397 builder->fsCodeAppendf("\t\tfloat alpha = 1.0;\n");
398 builder->fsCodeAppendf("\t\talpha *= (fragPosShifted.x - %s.x) > -0.5 ? 1.0 : 0.0;\n", rectName);
399 builder->fsCodeAppendf("\t\talpha *= (%s.z - fragPosShifted.x) >= -0.5 ? 1.0 : 0.0;\n", rectName);
400 }
401 builder->fsCodeAppendf("\t\t%s = %s;\n", outputColor,
402 (GrGLSLExpr4(inputColor) * GrGLSLExpr1("alpha")).c_st r());
403 }
404
405 void GLDashingLineEffect::setData(const GrGLUniformManager& uman, const GrDrawEf fect& drawEffect) {
406 const DashingLineEffect& de = drawEffect.castEffect<DashingLineEffect>();
407 const SkRect& rect = de.getRect();
408 SkScalar intervalLength = de.getIntervalLength();
409 if (rect != fPrevRect || intervalLength != fPrevIntervalLength) {
410 uman.set4f(fRectUniform, rect.fLeft + 0.5f, rect.fTop + 0.5f,
411 rect.fRight - 0.5f, rect.fBottom - 0.5f);
412 uman.set1f(fIntervalUniform, intervalLength);
413 fPrevRect = rect;
414 fPrevIntervalLength = intervalLength;
415 }
416 }
417
418 GrGLEffect::EffectKey GLDashingLineEffect::GenKey(const GrDrawEffect& drawEffect ,
419 const GrGLCaps&) {
420 const DashingLineEffect& de = drawEffect.castEffect<DashingLineEffect>();
421 return de.getEdgeType();
422 }
423
424 //////////////////////////////////////////////////////////////////////////////
425
426 GrEffectRef* DashingLineEffect::Create(GrEffectEdgeType edgeType, const DashInfo & info,
427 const SkMatrix& matrix, SkScalar strokeWidt h) {
428 if (info.fCount != 2) {
429 return NULL;
430 }
431
432 return CreateEffectRef(AutoEffectUnref(SkNEW_ARGS(DashingLineEffect,
433 (edgeType, info, matrix, s trokeWidth))));
434 }
435
436 DashingLineEffect::~DashingLineEffect() {}
437
438 void DashingLineEffect::getConstantColorComponents(GrColor* color, uint32_t* val idFlags) const {
439 *validFlags = 0;
440 }
441
442 const GrBackendEffectFactory& DashingLineEffect::getFactory() const {
443 return GrTBackendEffectFactory<DashingLineEffect>::getInstance();
444 }
445
446 DashingLineEffect::DashingLineEffect(GrEffectEdgeType edgeType, const DashInfo& info,
447 const SkMatrix& matrix, SkScalar strokeWidth)
448 : fEdgeType(edgeType)
449 , fCoordTransform(kLocal_GrCoordSet, matrix) {
450 SkScalar onLen = info.fIntervals[0];
451 SkScalar offLen = info.fIntervals[1];
452 SkScalar halfOffLen = SkScalarHalf(offLen);
453 SkScalar halfStroke = SkScalarHalf(strokeWidth);
454 fIntervalLength = onLen + offLen;
455 fRect.set(halfOffLen, -halfStroke, halfOffLen + onLen, halfStroke);
456
457 addCoordTransform(&fCoordTransform);
458 }
459
460 bool DashingLineEffect::onIsEqual(const GrEffect& other) const {
461 const DashingLineEffect& de = CastEffect<DashingLineEffect>(other);
462 return (fEdgeType == de.fEdgeType &&
463 fCoordTransform == de.fCoordTransform &&
464 fRect == de.fRect &&
465 fIntervalLength == de.fIntervalLength);
466 }
467
468 GR_DEFINE_EFFECT_TEST(DashingLineEffect);
469
470 GrEffectRef* DashingLineEffect::TestCreate(SkRandom* random,
471 GrContext*,
472 const GrDrawTargetCaps& caps,
473 GrTexture*[]) {
474 GrEffectRef* effect;
475 SkMatrix m;
476 m.reset();
477 GrEffectEdgeType edgeType = static_cast<GrEffectEdgeType>(random->nextULessT han(
478 kGrEffectEdgeTypeCnt));
479 SkScalar strokeWidth = random->nextRangeScalar(0, 100.f);
480 DashInfo info;
481 info.fCount = 2;
482 SkAutoTArray<SkScalar> intervals(info.fCount);
483 info.fIntervals = intervals.get();
484 info.fIntervals[0] = random->nextRangeScalar(0, 10.f);
485 info.fIntervals[1] = random->nextRangeScalar(0, 10.f);
486 info.fPhase = random->nextRangeScalar(0, info.fIntervals[0] + info.fInterval s[1]);
487
488 effect = DashingLineEffect::Create(edgeType, info, m, strokeWidth);
489 return effect;
490 }
491
492 //////////////////////////////////////////////////////////////////////////////
493
494 GrEffectRef* GrDashingEffect::Create(GrEffectEdgeType edgeType, const SkPathEffe ct::DashInfo& info,
495 const SkMatrix& matrix, SkScalar strokeWidt h) {
496 return DashingLineEffect::Create(edgeType, info, matrix, strokeWidth);
497 }
OLDNEW
« no previous file with comments | « src/gpu/effects/GrDashingEffect.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698