SkRRect.h revision c2f7824436d05da6e8514d06a54773538aace028
1/*
2 * Copyright 2012 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#ifndef SkRRect_DEFINED
9#define SkRRect_DEFINED
10
11#include "SkRect.h"
12#include "SkPoint.h"
13
14class SkPath;
15class SkMatrix;
16
17// Path forward:
18//   core work
19//      add validate method (all radii positive, all radii sums < rect size, etc.)
20//      add contains(SkRect&)  - for clip stack
21//      add contains(SkRRect&) - for clip stack
22//      add heart rect computation (max rect inside RR)
23//      add 9patch rect computation
24//      add growToInclude(SkPath&)
25//   analysis
26//      use growToInclude to fit skp round rects & generate stats (RRs vs. real paths)
27//      check on # of rectorus's the RRs could handle
28//   rendering work
29//      update SkPath.addRRect() to only use quads
30//      add GM and bench
31//   further out
32//      detect and triangulate RRectorii rather than falling back to SW in Ganesh
33//
34
35/** \class SkRRect
36
37    The SkRRect class represents a rounded rect with a potentially different
38    radii for each corner. It does not have a constructor so must be
39    initialized with one of the initialization functions (e.g., setEmpty,
40    setRectRadii, etc.)
41
42    This class is intended to roughly match CSS' border-*-*-radius capabilities.
43    This means:
44        If either of a corner's radii are 0 the corner will be square.
45        Negative radii are not allowed (they are clamped to zero).
46        If the corner curves overlap they will be proportionally reduced to fit.
47*/
48class SK_API SkRRect {
49public:
50    /**
51     * Enum to capture the various possible subtypes of RR. Accessed
52     * by type(). The subtypes become progressively less restrictive.
53     */
54    enum Type {
55        // !< Internal indicator that the sub type must be computed.
56        kUnknown_Type = -1,
57
58        // !< The RR is empty
59        kEmpty_Type,
60
61        //!< The RR is actually a (non-empty) rect (i.e., at least one radius
62        //!< at each corner is zero)
63        kRect_Type,
64
65        //!< The RR is actually a (non-empty) oval (i.e., all x radii are equal
66        //!< and >= width/2 and all the y radii are equal and >= height/2
67        kOval_Type,
68
69        //!< The RR is non-empty and all the x radii are equal & all y radii
70        //!< are equal but it is not an oval (i.e., there are lines between
71        //!< the curves) nor a rect (i.e., both radii are non-zero)
72        kSimple_Type,
73
74        //!< A fully general (non-empty) RR. Some of the x and/or y radii are
75        //!< different from the others and there must be one corner where
76        //!< both radii are non-zero.
77        kComplex_Type,
78    };
79
80    /**
81     * Returns the RR's sub type.
82     */
83    Type getType() const {
84        SkDEBUGCODE(this->validate();)
85
86        if (kUnknown_Type == fType) {
87            this->computeType();
88        }
89        SkASSERT(kUnknown_Type != fType);
90        return fType;
91    }
92
93    Type type() const { return this->getType(); }
94
95    inline bool isEmpty() const { return kEmpty_Type == this->getType(); }
96    inline bool isRect() const { return kRect_Type == this->getType(); }
97    inline bool isOval() const { return kOval_Type == this->getType(); }
98    inline bool isSimple() const { return kSimple_Type == this->getType(); }
99    inline bool isSimpleCircular() const {
100        return this->isSimple() && fRadii[0].fX == fRadii[0].fY;
101    }
102    inline bool isComplex() const { return kComplex_Type == this->getType(); }
103
104    SkScalar width() const { return fRect.width(); }
105    SkScalar height() const { return fRect.height(); }
106
107    /**
108     * Set this RR to the empty rectangle (0,0,0,0) with 0 x & y radii.
109     */
110    void setEmpty() {
111        fRect.setEmpty();
112        memset(fRadii, 0, sizeof(fRadii));
113        fType = kEmpty_Type;
114
115        SkDEBUGCODE(this->validate();)
116    }
117
118    /**
119     * Set this RR to match the supplied rect. All radii will be 0.
120     */
121    void setRect(const SkRect& rect) {
122        if (rect.isEmpty()) {
123            this->setEmpty();
124            return;
125        }
126
127        fRect = rect;
128        memset(fRadii, 0, sizeof(fRadii));
129        fType = kRect_Type;
130
131        SkDEBUGCODE(this->validate();)
132    }
133
134    /**
135     * Set this RR to match the supplied oval. All x radii will equal half the
136     * width and all y radii will equal half the height.
137     */
138    void setOval(const SkRect& oval) {
139        if (oval.isEmpty()) {
140            this->setEmpty();
141            return;
142        }
143
144        SkScalar xRad = SkScalarHalf(oval.width());
145        SkScalar yRad = SkScalarHalf(oval.height());
146
147        fRect = oval;
148        for (int i = 0; i < 4; ++i) {
149            fRadii[i].set(xRad, yRad);
150        }
151        fType = kOval_Type;
152
153        SkDEBUGCODE(this->validate();)
154    }
155
156    /**
157     * Initialize the RR with the same radii for all four corners.
158     */
159    void setRectXY(const SkRect& rect, SkScalar xRad, SkScalar yRad);
160
161    /**
162     * Initialize the RR with potentially different radii for all four corners.
163     */
164    void setRectRadii(const SkRect& rect, const SkVector radii[4]);
165
166    // The radii are stored in UL, UR, LR, LL order.
167    enum Corner {
168        kUpperLeft_Corner,
169        kUpperRight_Corner,
170        kLowerRight_Corner,
171        kLowerLeft_Corner
172    };
173
174    const SkRect& rect() const { return fRect; }
175    const SkVector& radii(Corner corner) const { return fRadii[corner]; }
176    const SkRect& getBounds() const { return fRect; }
177
178    /**
179     *  When a rrect is simple, all of its radii are equal. This returns one
180     *  of those radii. This call requires the rrect to be non-complex.
181     */
182    const SkVector& getSimpleRadii() const {
183        SkASSERT(!this->isComplex());
184        return fRadii[0];
185    }
186
187    friend bool operator==(const SkRRect& a, const SkRRect& b) {
188        return a.fRect == b.fRect &&
189               SkScalarsEqual(a.fRadii[0].asScalars(),
190                              b.fRadii[0].asScalars(), 8);
191    }
192
193    friend bool operator!=(const SkRRect& a, const SkRRect& b) {
194        return a.fRect != b.fRect ||
195               !SkScalarsEqual(a.fRadii[0].asScalars(),
196                               b.fRadii[0].asScalars(), 8);
197    }
198
199    /**
200     *  Call inset on the bounds, and adjust the radii to reflect what happens
201     *  in stroking: If the corner is sharp (no curvature), leave it alone,
202     *  otherwise we grow/shrink the radii by the amount of the inset. If a
203     *  given radius becomes negative, it is pinned to 0.
204     *
205     *  It is valid for dst == this.
206     */
207    void inset(SkScalar dx, SkScalar dy, SkRRect* dst) const;
208
209    void inset(SkScalar dx, SkScalar dy) {
210        this->inset(dx, dy, this);
211    }
212
213    /**
214     *  Call outset on the bounds, and adjust the radii to reflect what happens
215     *  in stroking: If the corner is sharp (no curvature), leave it alone,
216     *  otherwise we grow/shrink the radii by the amount of the inset. If a
217     *  given radius becomes negative, it is pinned to 0.
218     *
219     *  It is valid for dst == this.
220     */
221    void outset(SkScalar dx, SkScalar dy, SkRRect* dst) const {
222        this->inset(-dx, -dy, dst);
223    }
224    void outset(SkScalar dx, SkScalar dy) {
225        this->inset(-dx, -dy, this);
226    }
227
228    /**
229     *  Returns true if 'rect' is wholy inside the RR, and both
230     *  are not empty.
231     */
232    bool contains(const SkRect& rect) const;
233
234    SkDEBUGCODE(void validate() const;)
235
236    enum {
237        kSizeInMemory = 12 * sizeof(SkScalar)
238    };
239
240    /**
241     *  Write the rrect into the specified buffer. This is guaranteed to always
242     *  write kSizeInMemory bytes, and that value is guaranteed to always be
243     *  a multiple of 4. Return kSizeInMemory.
244     */
245    size_t writeToMemory(void* buffer) const;
246
247    /**
248     * Reads the rrect from the specified buffer
249     *
250     * If the specified buffer is large enough, this will read kSizeInMemory bytes,
251     * and that value is guaranteed to always be a multiple of 4.
252     *
253     * @param buffer Memory to read from
254     * @param length Amount of memory available in the buffer
255     * @return number of bytes read (must be a multiple of 4) or
256     *         0 if there was not enough memory available
257     */
258    size_t readFromMemory(const void* buffer, size_t length);
259
260    /**
261     *  Transform by the specified matrix, and put the result in dst.
262     *
263     *  @param matrix SkMatrix specifying the transform. Must only contain
264     *      scale and/or translate, or this call will fail.
265     *  @param dst SkRRect to store the result. It is an error to use this,
266     *      which would make this function no longer const.
267     *  @return true on success, false on failure. If false, dst is unmodified.
268     */
269    bool transform(const SkMatrix& matrix, SkRRect* dst) const;
270
271private:
272    SkRect fRect;
273    // Radii order is UL, UR, LR, LL. Use Corner enum to index into fRadii[]
274    SkVector fRadii[4];
275    mutable Type fType;
276    // TODO: add padding so we can use memcpy for flattening and not copy
277    // uninitialized data
278
279    void computeType() const;
280    bool checkCornerContainment(SkScalar x, SkScalar y) const;
281
282    // to access fRadii directly
283    friend class SkPath;
284};
285
286#endif
287