Flutter Impeller
tessellator.h
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_H_
6 #define FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_H_
7 
8 #include <functional>
9 #include <memory>
10 #include <vector>
11 
12 #include "impeller/core/formats.h"
15 #include "impeller/geometry/arc.h"
19 #include "impeller/geometry/trig.h"
20 
21 namespace impeller {
22 
23 /// The size of the point arena buffer stored on the tessellator.
24 [[maybe_unused]]
25 static constexpr size_t kPointArenaSize = 4096u;
26 
27 //------------------------------------------------------------------------------
28 /// @brief A utility that generates triangles of the specified fill type
29 /// given a polyline. This happens on the CPU.
30 ///
31 /// Also contains functionality for optimized generation of circles
32 /// and ellipses.
33 ///
34 /// This object is not thread safe, and its methods must not be
35 /// called from multiple threads.
36 ///
37 class Tessellator {
38  public:
39  /// Essentially just a vector of Trig objects, but supports storing a
40  /// reference to either a cached vector or a locally generated vector.
41  /// The constructor will fill the vector with quarter circular samples
42  /// for the indicated number of equal divisions if the vector is new.
43  ///
44  /// A given instance of Trigs will always contain at least 2 entries
45  /// which is the minimum number of samples to traverse a quarter circle
46  /// in a single step. The first sample will always be (0, 1) and the last
47  /// sample will always be (1, 0).
48  class Trigs {
49  public:
50  explicit Trigs(Scalar pixel_radius);
51 
52  // Utility forwards of the indicated vector methods.
53  size_t inline size() const { return trigs_.size(); }
54  std::vector<Trig>::iterator inline begin() const { return trigs_.begin(); }
55  std::vector<Trig>::iterator inline end() const { return trigs_.end(); }
56  const inline Trig& operator[](size_t index) const { return trigs_[index]; }
57 
58  size_t inline GetSteps() const { return trigs_.size() - 1u; }
59 
60  private:
61  friend class Tessellator;
62 
63  explicit Trigs(std::vector<Trig>& trigs, size_t divisions) : trigs_(trigs) {
64  FML_DCHECK(divisions >= 1);
65  init(divisions);
66  FML_DCHECK(trigs_.size() == divisions + 1);
67  }
68 
69  explicit Trigs(size_t divisions)
70  : local_storage_(std::make_unique<std::vector<Trig>>()),
71  trigs_(*local_storage_) {
72  FML_DCHECK(divisions >= 1);
73  init(divisions);
74  FML_DCHECK(trigs_.size() == divisions + 1);
75  }
76 
77  // nullptr if a cached vector is used, otherwise the actual storage
78  std::unique_ptr<std::vector<Trig>> local_storage_;
79 
80  // Whether or not a cached vector or the local storage is used, this
81  // this reference will always be valid
82  std::vector<Trig>& trigs_;
83 
84  // Fill the vector with the indicated number of equal divisions of
85  // trigonometric values if it is empty.
86  void init(size_t divisions);
87  };
88 
89  enum class Result {
90  kSuccess,
93  };
94 
95  /// @brief A callback function for a |VertexGenerator| to deliver
96  /// the vertices it computes as |Point| objects.
97  using TessellatedVertexProc = std::function<void(const Point& p)>;
98 
99  /// @brief An object which produces a list of vertices as |Point|s that
100  /// tessellate a previously provided shape and delivers the vertices
101  /// through a |TessellatedVertexProc| callback.
102  ///
103  /// The object can also provide advance information on how many
104  /// vertices it will generate.
105  ///
106  /// @see |Tessellator::FilledCircle|
107  /// @see |Tessellator::StrokedCircle|
108  /// @see |Tessellator::RoundCapLine|
109  /// @see |Tessellator::FilledEllipse|
111  public:
112  /// @brief Returns the |PrimitiveType| that describes the relationship
113  /// among the list of vertices produced by the |GenerateVertices|
114  /// method.
115  ///
116  /// Most generators will deliver |kTriangleStrip| triangles
117  virtual PrimitiveType GetTriangleType() const = 0;
118 
119  /// @brief Returns the number of vertices that the generator plans to
120  /// produce, if known.
121  ///
122  /// This value is advisory only and can be used to reserve space
123  /// where the vertices will be placed, but the count may be an
124  /// estimate.
125  ///
126  /// Implementations are encouraged to avoid overestimating
127  /// the count by too large a number and to provide a best
128  /// guess so as to minimize potential buffer reallocations
129  /// as the vertices are delivered.
130  virtual size_t GetVertexCount() const = 0;
131 
132  /// @brief Generate the vertices and deliver them in the necessary
133  /// order (as required by the PrimitiveType) to the given
134  /// callback function.
135  virtual void GenerateVertices(const TessellatedVertexProc& proc) const = 0;
136  };
137 
138  /// @brief The |VertexGenerator| implementation common to all shapes
139  /// that are based on a polygonal representation of an ellipse.
141  public:
142  /// |VertexGenerator|
143  PrimitiveType GetTriangleType() const override {
145  }
146 
147  /// |VertexGenerator|
148  size_t GetVertexCount() const override {
149  return trigs_.size() * vertices_per_trig_;
150  }
151 
152  /// |VertexGenerator|
153  void GenerateVertices(const TessellatedVertexProc& proc) const override {
154  impl_(trigs_, data_, proc);
155  }
156 
157  private:
158  friend class Tessellator;
159 
160  struct Data {
161  // Circles and Ellipses only use one of these points.
162  // RoundCapLines use both as the endpoints of the unexpanded line.
163  // A round rect can specify its interior rectangle by using the
164  // 2 points as opposing corners.
165  const Point reference_centers[2];
166  // Circular shapes have the same value in radii.width and radii.height
167  const Size radii;
168  // half_width is only used in cases where the generator will be
169  // generating 2 different outlines, such as StrokedCircle
170  const Scalar half_width;
171  };
172 
173  typedef void GeneratorProc(const Trigs& trigs,
174  const Data& data,
175  const TessellatedVertexProc& proc);
176 
177  GeneratorProc& impl_;
178  const Trigs trigs_;
179  const Data data_;
180  const size_t vertices_per_trig_;
181 
182  EllipticalVertexGenerator(GeneratorProc& generator,
183  Trigs&& trigs,
184  PrimitiveType triangle_type,
185  size_t vertices_per_trig,
186  Data&& data);
187  };
188 
189  /// @brief The |VertexGenerator| implementation common to all shapes
190  /// that are based on a polygonal representation of an ellipse.
191  class ArcVertexGenerator : public virtual VertexGenerator {
192  public:
193  /// |VertexGenerator|
194  PrimitiveType GetTriangleType() const override;
195 
196  /// |VertexGenerator|
197  size_t GetVertexCount() const override;
198 
199  /// |VertexGenerator|
200  void GenerateVertices(const TessellatedVertexProc& proc) const override;
201 
202  private:
203  friend class Tessellator;
204 
205  const Arc::Iteration iteration_;
206  const Trigs trigs_;
207  const Rect oval_bounds_;
208  const bool use_center_;
209  const Scalar half_width_;
210  const Cap cap_;
211  const bool supports_triangle_fans_;
212 
213  ArcVertexGenerator(const Arc::Iteration& iteration,
214  Trigs&& trigs,
215  const Rect& oval_bounds,
216  bool use_center,
217  bool supports_triangle_fans);
218 
219  ArcVertexGenerator(const Arc::Iteration& iteration,
220  Trigs&& trigs,
221  const Rect& oval_bounds,
222  Scalar half_width,
223  Cap cap);
224  };
225 
226  Tessellator();
227 
228  virtual ~Tessellator();
229 
230  //----------------------------------------------------------------------------
231  /// @brief Given a convex path, create a triangle fan structure.
232  ///
233  /// @param[in] path The path to tessellate.
234  /// @param[in] host_buffer The host buffer for allocation of vertices/index
235  /// data.
236  /// @param[in] tolerance The tolerance value for conversion of the path to
237  /// a polyline. This value is often derived from the
238  /// Matrix::GetMaxBasisLengthXY of the CTM applied to
239  /// the path for rendering.
240  ///
241  /// @return A vertex buffer containing all data from the provided curve.
243  HostBuffer& data_host_buffer,
244  HostBuffer& indexes_host_buffer,
245  Scalar tolerance,
246  bool supports_primitive_restart = false,
247  bool supports_triangle_fan = false);
248 
249  /// Visible for testing.
250  ///
251  /// This method only exists for the ease of benchmarking without using the
252  /// real allocator needed by the [host_buffer].
253  static void TessellateConvexInternal(const PathSource& path,
254  std::vector<Point>& point_buffer,
255  std::vector<uint16_t>& index_buffer,
256  Scalar tolerance);
257 
258  //----------------------------------------------------------------------------
259  /// @brief The pixel tolerance used by the algorighm to determine how
260  /// many divisions to create for a circle.
261  ///
262  /// No point on the polygon of vertices should deviate from the
263  /// true circle by more than this tolerance.
264  static constexpr Scalar kCircleTolerance = 0.1f;
265 
266  /// @brief Create a |VertexGenerator| that can produce vertices for
267  /// a filled circle of the given radius around the given center
268  /// with enough polygon sub-divisions to provide reasonable
269  /// fidelity when viewed under the given view transform.
270  ///
271  /// Note that the view transform is only used to choose the
272  /// number of sample points to use per quarter circle and the
273  /// returned points are not transformed by it, instead they are
274  /// relative to the coordinate space of the center point.
275  EllipticalVertexGenerator FilledCircle(const Matrix& view_transform,
276  const Point& center,
277  Scalar radius);
278 
279  /// @brief Create a |VertexGenerator| that can produce vertices for
280  /// a stroked circle of the given radius and half_width around
281  /// the given shared center with enough polygon sub-divisions
282  /// to provide reasonable fidelity when viewed under the given
283  /// view transform. The outer edge of the stroked circle is
284  /// generated at (radius + half_width) and the inner edge is
285  /// generated at (radius - half_width).
286  ///
287  /// Note that the view transform is only used to choose the
288  /// number of sample points to use per quarter circle and the
289  /// returned points are not transformed by it, instead they are
290  /// relative to the coordinate space of the center point.
291  EllipticalVertexGenerator StrokedCircle(const Matrix& view_transform,
292  const Point& center,
293  Scalar radius,
294  Scalar half_width);
295 
296  /// @brief Create a |VertexGenerator| that can produce vertices for
297  /// a stroked arc inscribed within the given oval_bounds with
298  /// the given stroke half_width with enough polygon sub-divisions
299  /// to provide reasonable fidelity when viewed under the given
300  /// view transform. The outer edge of the stroked arc is
301  /// generated at (radius + half_width) and the inner edge is
302  /// generated at (radius - half_width).
303  ///
304  /// Note that the view transform is only used to choose the
305  /// number of sample points to use per quarter circle and the
306  /// returned points are not transformed by it, instead they are
307  /// relative to the coordinate space of the oval bounds.
308  ArcVertexGenerator FilledArc(const Matrix& view_transform,
309  const Arc& arc,
310  bool supports_triangle_fans);
311 
312  /// @brief Create a |VertexGenerator| that can produce vertices for
313  /// a stroked arc inscribed within the given oval_bounds with
314  /// the given stroke half_width with enough polygon sub-divisions
315  /// to provide reasonable fidelity when viewed under the given
316  /// view transform. The outer edge of the stroked arc is
317  /// generated at (radius + half_width) and the inner edge is
318  /// generated at (radius - half_width).
319  ///
320  /// Note that the arc may not include the center and its bounds
321  /// must be a perfect circle (width == height)
322  ///
323  /// Note that the view transform is only used to choose the
324  /// number of sample points to use per quarter circle and the
325  /// returned points are not transformed by it, instead they are
326  /// relative to the coordinate space of the oval bounds.
327  ArcVertexGenerator StrokedArc(const Matrix& view_transform,
328  const Arc& arc,
329  Cap cap,
330  Scalar half_width);
331 
332  /// @brief Create a |VertexGenerator| that can produce vertices for
333  /// a line with round end caps of the given radius with enough
334  /// polygon sub-divisions to provide reasonable fidelity when
335  /// viewed under the given view transform.
336  ///
337  /// Note that the view transform is only used to choose the
338  /// number of sample points to use per quarter circle and the
339  /// returned points are not transformed by it, instead they are
340  /// relative to the coordinate space of the two points.
341  EllipticalVertexGenerator RoundCapLine(const Matrix& view_transform,
342  const Point& p0,
343  const Point& p1,
344  Scalar radius);
345 
346  /// @brief Create a |VertexGenerator| that can produce vertices for
347  /// a filled ellipse inscribed within the given bounds with
348  /// enough polygon sub-divisions to provide reasonable
349  /// fidelity when viewed under the given view transform.
350  ///
351  /// Note that the view transform is only used to choose the
352  /// number of sample points to use per quarter circle and the
353  /// returned points are not transformed by it, instead they are
354  /// relative to the coordinate space of the bounds.
355  EllipticalVertexGenerator FilledEllipse(const Matrix& view_transform,
356  const Rect& bounds);
357 
358  /// @brief Create a |VertexGenerator| that can produce vertices for
359  /// a filled round rect within the given bounds and corner radii
360  /// with enough polygon sub-divisions to provide reasonable
361  /// fidelity when viewed under the given view transform.
362  ///
363  /// Note that the view transform is only used to choose the
364  /// number of sample points to use per quarter circle and the
365  /// returned points are not transformed by it, instead they are
366  /// relative to the coordinate space of the bounds.
367  EllipticalVertexGenerator FilledRoundRect(const Matrix& view_transform,
368  const Rect& bounds,
369  const Size& radii);
370 
371  /// Retrieve a pre-allocated arena of kPointArenaSize points.
372  std::vector<Point>& GetStrokePointCache();
373 
374  /// Return a vector of Trig (cos, sin pairs) structs for a 90 degree
375  /// circle quadrant of the specified pixel radius
376  Trigs GetTrigsForDeviceRadius(Scalar pixel_radius);
377 
378  protected:
379  /// Used for polyline generation.
380  std::unique_ptr<std::vector<Point>> point_buffer_;
381  std::unique_ptr<std::vector<uint16_t>> index_buffer_;
382  /// Used for stroke path generation.
383  std::vector<Point> stroke_points_;
384 
385  private:
386  // Data for various Circle/EllipseGenerator classes, cached per
387  // Tessellator instance which is usually the foreground life of an app
388  // if not longer.
389  static constexpr size_t kCachedTrigCount = 300;
390  std::vector<Trig> precomputed_trigs_[kCachedTrigCount];
391 
392  Trigs GetTrigsForDivisions(size_t divisions);
393 
394  static void GenerateFilledCircle(const Trigs& trigs,
395  const EllipticalVertexGenerator::Data& data,
396  const TessellatedVertexProc& proc);
397 
398  static void GenerateStrokedCircle(const Trigs& trigs,
399  const EllipticalVertexGenerator::Data& data,
400  const TessellatedVertexProc& proc);
401 
402  static void GenerateFilledArcFan(const Trigs& trigs,
403  const Arc::Iteration& iteration,
404  const Rect& oval_bounds,
405  bool use_center,
406  const TessellatedVertexProc& proc);
407 
408  static void GenerateFilledArcStrip(const Trigs& trigs,
409  const Arc::Iteration& iteration,
410  const Rect& oval_bounds,
411  bool use_center,
412  const TessellatedVertexProc& proc);
413 
414  static void GenerateStrokedArc(const Trigs& trigs,
415  const Arc::Iteration& iteration,
416  const Rect& oval_bounds,
417  Scalar half_width,
418  Cap cap,
419  const TessellatedVertexProc& proc);
420 
421  static void GenerateRoundCapLine(const Trigs& trigs,
422  const EllipticalVertexGenerator::Data& data,
423  const TessellatedVertexProc& proc);
424 
425  static void GenerateFilledEllipse(const Trigs& trigs,
426  const EllipticalVertexGenerator::Data& data,
427  const TessellatedVertexProc& proc);
428 
429  static void GenerateFilledRoundRect(
430  const Trigs& trigs,
431  const EllipticalVertexGenerator::Data& data,
432  const TessellatedVertexProc& proc);
433 
434  Tessellator(const Tessellator&) = delete;
435 
436  Tessellator& operator=(const Tessellator&) = delete;
437 };
438 
439 } // namespace impeller
440 
441 #endif // FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_H_
bool use_center
The |VertexGenerator| implementation common to all shapes that are based on a polygonal representatio...
Definition: tessellator.h:191
size_t GetVertexCount() const override
|VertexGenerator|
Definition: tessellator.cc:522
PrimitiveType GetTriangleType() const override
|VertexGenerator|
Definition: tessellator.cc:516
void GenerateVertices(const TessellatedVertexProc &proc) const override
|VertexGenerator|
Definition: tessellator.cc:542
The |VertexGenerator| implementation common to all shapes that are based on a polygonal representatio...
Definition: tessellator.h:140
PrimitiveType GetTriangleType() const override
|VertexGenerator|
Definition: tessellator.h:143
size_t GetVertexCount() const override
|VertexGenerator|
Definition: tessellator.h:148
void GenerateVertices(const TessellatedVertexProc &proc) const override
|VertexGenerator|
Definition: tessellator.h:153
std::vector< Trig >::iterator begin() const
Definition: tessellator.h:54
std::vector< Trig >::iterator end() const
Definition: tessellator.h:55
Trigs(Scalar pixel_radius)
Definition: tessellator.cc:412
const Trig & operator[](size_t index) const
Definition: tessellator.h:56
An object which produces a list of vertices as |Point|s that tessellate a previously provided shape a...
Definition: tessellator.h:110
virtual size_t GetVertexCount() const =0
Returns the number of vertices that the generator plans to produce, if known.
virtual PrimitiveType GetTriangleType() const =0
Returns the |PrimitiveType| that describes the relationship among the list of vertices produced by th...
virtual void GenerateVertices(const TessellatedVertexProc &proc) const =0
Generate the vertices and deliver them in the necessary order (as required by the PrimitiveType) to t...
A utility that generates triangles of the specified fill type given a polyline. This happens on the C...
Definition: tessellator.h:37
Trigs GetTrigsForDeviceRadius(Scalar pixel_radius)
Definition: tessellator.cc:310
std::vector< Point > stroke_points_
Used for stroke path generation.
Definition: tessellator.h:383
EllipticalVertexGenerator RoundCapLine(const Matrix &view_transform, const Point &p0, const Point &p1, Scalar radius)
Create a |VertexGenerator| that can produce vertices for a line with round end caps of the given radi...
Definition: tessellator.cc:584
std::vector< Point > & GetStrokePointCache()
Retrieve a pre-allocated arena of kPointArenaSize points.
Definition: tessellator.cc:306
EllipticalVertexGenerator FilledRoundRect(const Matrix &view_transform, const Rect &bounds, const Size &radii)
Create a |VertexGenerator| that can produce vertices for a filled round rect within the given bounds ...
Definition: tessellator.cc:628
static constexpr Scalar kCircleTolerance
The pixel tolerance used by the algorighm to determine how many divisions to create for a circle.
Definition: tessellator.h:264
VertexBuffer TessellateConvex(const PathSource &path, HostBuffer &data_host_buffer, HostBuffer &indexes_host_buffer, Scalar tolerance, bool supports_primitive_restart=false, bool supports_triangle_fan=false)
Given a convex path, create a triangle fan structure.
Definition: tessellator.cc:314
EllipticalVertexGenerator FilledCircle(const Matrix &view_transform, const Point &center, Scalar radius)
Create a |VertexGenerator| that can produce vertices for a filled circle of the given radius around t...
Definition: tessellator.cc:453
ArcVertexGenerator StrokedArc(const Matrix &view_transform, const Arc &arc, Cap cap, Scalar half_width)
Create a |VertexGenerator| that can produce vertices for a stroked arc inscribed within the given ova...
Definition: tessellator.cc:568
static void TessellateConvexInternal(const PathSource &path, std::vector< Point > &point_buffer, std::vector< uint16_t > &index_buffer, Scalar tolerance)
Definition: tessellator.cc:400
EllipticalVertexGenerator StrokedCircle(const Matrix &view_transform, const Point &center, Scalar radius, Scalar half_width)
Create a |VertexGenerator| that can produce vertices for a stroked circle of the given radius and hal...
Definition: tessellator.cc:469
std::unique_ptr< std::vector< Point > > point_buffer_
Used for polyline generation.
Definition: tessellator.h:380
std::unique_ptr< std::vector< uint16_t > > index_buffer_
Definition: tessellator.h:381
EllipticalVertexGenerator FilledEllipse(const Matrix &view_transform, const Rect &bounds)
Create a |VertexGenerator| that can produce vertices for a filled ellipse inscribed within the given ...
Definition: tessellator.cc:607
std::function< void(const Point &p)> TessellatedVertexProc
A callback function for a |VertexGenerator| to deliver the vertices it computes as |Point| objects.
Definition: tessellator.h:97
ArcVertexGenerator FilledArc(const Matrix &view_transform, const Arc &arc, bool supports_triangle_fans)
Create a |VertexGenerator| that can produce vertices for a stroked arc inscribed within the given ova...
Definition: tessellator.cc:557
PrimitiveType
Decides how backend draws pixels based on input vertices.
Definition: formats.h:352
float Scalar
Definition: scalar.h:19
Cap
An enum that describes ways to decorate the end of a path contour.
Tessellator::ArcVertexGenerator ArcVertexGenerator
Definition: tessellator.cc:440
static constexpr size_t kPointArenaSize
The size of the point arena buffer stored on the tessellator.
Definition: tessellator.h:25
Definition: comparable.h:95
A 4x4 matrix using column-major storage.
Definition: matrix.h:37
A structure to store the sine and cosine of an angle.
Definition: trig.h:16
std::shared_ptr< const fml::Mapping > data
Definition: texture_gles.cc:68