DISTRHO Plugin Framework
NanoVG.hpp
1 /*
2  * DISTRHO Plugin Framework (DPF)
3  * Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com>
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any purpose with
6  * or without fee is hereby granted, provided that the above copyright notice and this
7  * permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
10  * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
11  * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
12  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
13  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
14  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 #ifndef DGL_NANO_WIDGET_HPP_INCLUDED
18 #define DGL_NANO_WIDGET_HPP_INCLUDED
19 
20 #include "Color.hpp"
21 #include "OpenGL.hpp"
22 #include "SubWidget.hpp"
23 #include "TopLevelWidget.hpp"
24 #include "StandaloneWindow.hpp"
25 
26 #ifdef _MSC_VER
27 # pragma warning(push)
28 # pragma warning(disable:4661) /* instantiated template classes whose methods are defined elsewhere */
29 #endif
30 
31 #ifndef DGL_NO_SHARED_RESOURCES
32 # define NANOVG_DEJAVU_SANS_TTF "__dpf_dejavusans_ttf__"
33 #endif
34 
35 struct NVGcontext;
36 struct NVGpaint;
37 
38 START_NAMESPACE_DGL
39 
40 // -----------------------------------------------------------------------
41 // Forward class names
42 
43 class NanoVG;
44 
45 // -----------------------------------------------------------------------
46 // NanoImage
47 
48 /**
49  NanoVG Image class.
50 
51  This implements NanoVG images as a C++ class where deletion is handled automatically.
52  Images need to be created within a NanoVG or NanoWidget class.
53  */
54 class NanoImage
55 {
56 private:
57  struct Handle {
58  NVGcontext* context;
59  int imageId;
60 
61  Handle() noexcept
62  : context(nullptr),
63  imageId(0) {}
64 
65  Handle(NVGcontext* c, int id) noexcept
66  : context(c),
67  imageId(id) {}
68  };
69 
70 public:
71  /**
72  Constructor for an invalid/null image.
73  */
74  NanoImage();
75 
76  /**
77  Constructor.
78  */
79  NanoImage(const Handle& handle);
80 
81  /**
82  Destructor.
83  */
84  ~NanoImage();
85 
86  /**
87  Create a new image without recreating the C++ class.
88  */
89  NanoImage& operator=(const Handle& handle);
90 
91  /**
92  Wherever this image is valid.
93  */
94  bool isValid() const noexcept;
95 
96  /**
97  Get size.
98  */
99  Size<uint> getSize() const noexcept;
100 
101  /**
102  Get the OpenGL texture handle.
103  */
104  GLuint getTextureHandle() const;
105 
106 private:
107  Handle fHandle;
108  Size<uint> fSize;
109  friend class NanoVG;
110 
111  /** @internal */
112  void _updateSize();
113 
114  DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoImage)
115 };
116 
117 // -----------------------------------------------------------------------
118 // NanoVG
119 
120 /**
121  NanoVG class.
122 
123  This class exposes the NanoVG drawing API.
124  All calls should be wrapped in beginFrame() and endFrame().
125 
126  @section State Handling
127  NanoVG contains state which represents how paths will be rendered.
128  The state contains transform, fill and stroke styles, text and font styles, and scissor clipping.
129 
130  @section Render styles
131  Fill and stroke render style can be either a solid color or a paint which is a gradient or a pattern.
132  Solid color is simply defined as a color value, different kinds of paints can be created
133  using linearGradient(), boxGradient(), radialGradient() and imagePattern().
134 
135  Current render style can be saved and restored using save() and restore().
136 
137  @section Transforms
138  The paths, gradients, patterns and scissor region are transformed by an transformation
139  matrix at the time when they are passed to the API.
140  The current transformation matrix is a affine matrix:
141  [sx kx tx]
142  [ky sy ty]
143  [ 0 0 1]
144  Where: sx,sy define scaling, kx,ky skewing, and tx,ty translation.
145  The last row is assumed to be 0,0,1 and is not stored.
146 
147  Apart from resetTransform(), each transformation function first creates
148  specific transformation matrix and pre-multiplies the current transformation by it.
149 
150  Current coordinate system (transformation) can be saved and restored using save() and restore().
151 
152  @section Images
153  NanoVG allows you to load jpg, png, psd, tga, pic and gif files to be used for rendering.
154  In addition you can upload your own image. The image loading is provided by stb_image.
155 
156  @section Paints
157  NanoVG supports four types of paints: linear gradient, box gradient, radial gradient and image pattern.
158  These can be used as paints for strokes and fills.
159 
160  @section Scissoring
161  Scissoring allows you to clip the rendering into a rectangle. This is useful for various
162  user interface cases like rendering a text edit or a timeline.
163 
164  @section Paths
165  Drawing a new shape starts with beginPath(), it clears all the currently defined paths.
166  Then you define one or more paths and sub-paths which describe the shape. The are functions
167  to draw common shapes like rectangles and circles, and lower level step-by-step functions,
168  which allow to define a path curve by curve.
169 
170  NanoVG uses even-odd fill rule to draw the shapes. Solid shapes should have counter clockwise
171  winding and holes should have counter clockwise order. To specify winding of a path you can
172  call pathWinding(). This is useful especially for the common shapes, which are drawn CCW.
173 
174  Finally you can fill the path using current fill style by calling fill(), and stroke it
175  with current stroke style by calling stroke().
176 
177  The curve segments and sub-paths are transformed by the current transform.
178 
179  @section Text
180  NanoVG allows you to load .ttf files and use the font to render text.
181 
182  The appearance of the text can be defined by setting the current text style
183  and by specifying the fill color. Common text and font settings such as
184  font size, letter spacing and text align are supported. Font blur allows you
185  to create simple text effects such as drop shadows.
186 
187  At render time the font face can be set based on the font handles or name.
188 
189  Font measure functions return values in local space, the calculations are
190  carried in the same resolution as the final rendering. This is done because
191  the text glyph positions are snapped to the nearest pixels sharp rendering.
192 
193  The local space means that values are not rotated or scale as per the current
194  transformation. For example if you set font size to 12, which would mean that
195  line height is 16, then regardless of the current scaling and rotation, the
196  returned line height is always 16. Some measures may vary because of the scaling
197  since aforementioned pixel snapping.
198 
199  While this may sound a little odd, the setup allows you to always render the
200  same way regardless of scaling. i.e. following works regardless of scaling:
201 
202  @code
203  const char* txt = "Text me up.";
204  vg.textBounds(x,y, txt, NULL, bounds);
205  vg.beginPath();
206  vg.roundedRect(bounds[0], bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1]);
207  vg.fill();
208  @endcode
209 
210  Note: currently only solid color fill is supported for text.
211  */
212 class NanoVG
213 {
214 public:
215  enum CreateFlags {
216  /**
217  Flag indicating if geometry based anti-aliasing is used (may not be needed when using MSAA).
218  */
220 
221  /**
222  Flag indicating if strokes should be drawn using stencil buffer. The rendering will be a little
223  slower, but path overlaps (i.e. self-intersecting or sharp turns) will be drawn just once.
224  */
226 
227  /**
228  Flag indicating that additional debug checks are done.
229  */
230  CREATE_DEBUG = 1 << 2,
231  };
232 
233  enum ImageFlags {
234  IMAGE_GENERATE_MIPMAPS = 1 << 0, // Generate mipmaps during creation of the image.
235  IMAGE_REPEAT_X = 1 << 1, // Repeat image in X direction.
236  IMAGE_REPEAT_Y = 1 << 2, // Repeat image in Y direction.
237  IMAGE_FLIP_Y = 1 << 3, // Flips (inverses) image in Y direction when rendered.
238  IMAGE_PREMULTIPLIED = 1 << 4 // Image data has premultiplied alpha.
239  };
240 
241  enum Align {
242  // Horizontal align
243  ALIGN_LEFT = 1 << 0, // Align horizontally to left (default).
244  ALIGN_CENTER = 1 << 1, // Align horizontally to center.
245  ALIGN_RIGHT = 1 << 2, // Align horizontally to right.
246  // Vertical align
247  ALIGN_TOP = 1 << 3, // Align vertically to top.
248  ALIGN_MIDDLE = 1 << 4, // Align vertically to middle.
249  ALIGN_BOTTOM = 1 << 5, // Align vertically to bottom.
250  ALIGN_BASELINE = 1 << 6 // Align vertically to baseline (default).
251  };
252 
253  enum LineCap {
254  BUTT,
255  ROUND,
256  SQUARE,
257  BEVEL,
258  MITER
259  };
260 
261  enum Solidity {
262  SOLID = 1, // CCW
263  HOLE = 2 // CW
264  };
265 
266  enum Winding {
267  CCW = 1, // Winding for solid shapes
268  CW = 2 // Winding for holes
269  };
270 
271  struct Paint {
272  float xform[6];
273  float extent[2];
274  float radius;
275  float feather;
276  Color innerColor;
277  Color outerColor;
278  int imageId;
279 
280  Paint() noexcept;
281 
282  /**
283  @internal
284  */
285  Paint(const NVGpaint&) noexcept;
286  operator NVGpaint() const noexcept;
287  };
288 
289  struct GlyphPosition {
290  const char* str; // Position of the glyph in the input string.
291  float x; // The x-coordinate of the logical glyph position.
292  float minx, maxx; // The bounds of the glyph shape.
293  };
294 
295  struct TextRow {
296  const char* start; // Pointer to the input text where the row starts.
297  const char* end; // Pointer to the input text where the row ends (one past the last character).
298  const char* next; // Pointer to the beginning of the next row.
299  float width; // Logical width of the row.
300  float minx, maxx; // Actual bounds of the row. Logical with and bounds can differ because of kerning and some parts over extending.
301  };
302 
303  typedef int FontId;
304 
305  /**
306  Constructor.
307  @see CreateFlags
308  */
309  NanoVG(int flags = CREATE_ANTIALIAS);
310 
311  /**
312  Constructor reusing a NanoVG context, used for subwidgets.
313  */
314  /*
315  NanoVG(NanoWidget* groupWidget);
316  */
317 
318  /**
319  Destructor.
320  */
321  virtual ~NanoVG();
322 
323  /**
324  Get the NanoVG context.
325  You should not need this under normal circumstances.
326  */
327  NVGcontext* getContext() const noexcept
328  {
329  return fContext;
330  }
331 
332  /**
333  Begin drawing a new frame.
334  */
335  void beginFrame(const uint width, const uint height, const float scaleFactor = 1.0f);
336 
337  /**
338  Begin drawing a new frame inside a widget.
339  */
340  void beginFrame(Widget* const widget);
341 
342  /**
343  Cancels drawing the current frame.
344  */
345  void cancelFrame();
346 
347  /**
348  Ends drawing flushing remaining render state.
349  */
350  void endFrame();
351 
352  /* --------------------------------------------------------------------
353  * State Handling */
354 
355  /**
356  Pushes and saves the current render state into a state stack.
357  A matching restore() must be used to restore the state.
358  */
359  void save();
360 
361  /**
362  Pops and restores current render state.
363  */
364  void restore();
365 
366  /**
367  Resets current render state to default values. Does not affect the render state stack.
368  */
369  void reset();
370 
371  /* --------------------------------------------------------------------
372  * Render styles */
373 
374  /**
375  Sets current stroke style to a solid color.
376  */
377  void strokeColor(const Color& color);
378 
379  /**
380  Sets current stroke style to a solid color, made from red, green, blue and alpha numeric values.
381  Values must be in [0..255] range.
382  */
383  void strokeColor(const int red, const int green, const int blue, const int alpha = 255);
384 
385  /**
386  Sets current stroke style to a solid color, made from red, green, blue and alpha numeric values.
387  Values must in [0..1] range.
388  */
389  void strokeColor(const float red, const float green, const float blue, const float alpha = 1.0f);
390 
391  /**
392  Sets current stroke style to a paint, which can be a one of the gradients or a pattern.
393  */
394  void strokePaint(const Paint& paint);
395 
396  /**
397  Sets current fill style to a solid color.
398  */
399  void fillColor(const Color& color);
400 
401  /**
402  Sets current fill style to a solid color, made from red, green, blue and alpha numeric values.
403  Values must be in [0..255] range.
404  */
405  void fillColor(const int red, const int green, const int blue, const int alpha = 255);
406 
407  /**
408  Sets current fill style to a solid color, made from red, green, blue and alpha numeric values.
409  Values must in [0..1] range.
410  */
411  void fillColor(const float red, const float green, const float blue, const float alpha = 1.0f);
412 
413  /**
414  Sets current fill style to a paint, which can be a one of the gradients or a pattern.
415  */
416  void fillPaint(const Paint& paint);
417 
418  /**
419  Sets the miter limit of the stroke style.
420  Miter limit controls when a sharp corner is beveled.
421  */
422  void miterLimit(float limit);
423 
424  /**
425  Sets the stroke width of the stroke style.
426  */
427  void strokeWidth(float size);
428 
429  /**
430  Sets how the end of the line (cap) is drawn,
431  Can be one of: BUTT, ROUND, SQUARE.
432  */
433  void lineCap(LineCap cap = BUTT);
434 
435  /**
436  Sets how sharp path corners are drawn.
437  Can be one of MITER, ROUND, BEVEL.
438  */
439  void lineJoin(LineCap join = MITER);
440 
441  /**
442  Sets the transparency applied to all rendered shapes.
443  Already transparent paths will get proportionally more transparent as well.
444  */
445  void globalAlpha(float alpha);
446 
447  /* --------------------------------------------------------------------
448  * Transforms */
449 
450  /**
451  Resets current transform to a identity matrix.
452  */
453  void resetTransform();
454 
455  /**
456  Pre-multiplies current coordinate system by specified matrix.
457  The parameters are interpreted as matrix as follows:
458  [a c e]
459  [b d f]
460  [0 0 1]
461  */
462  void transform(float a, float b, float c, float d, float e, float f);
463 
464  /**
465  Translates current coordinate system.
466  */
467  void translate(float x, float y);
468 
469  /**
470  Rotates current coordinate system. Angle is specified in radians.
471  */
472  void rotate(float angle);
473 
474  /**
475  Skews the current coordinate system along X axis. Angle is specified in radians.
476  */
477  void skewX(float angle);
478 
479  /**
480  Skews the current coordinate system along Y axis. Angle is specified in radians.
481  */
482  void skewY(float angle);
483 
484  /**
485  Scales the current coordinate system.
486  */
487  void scale(float x, float y);
488 
489  /**
490  Stores the top part (a-f) of the current transformation matrix in to the specified buffer.
491  [a c e]
492  [b d f]
493  [0 0 1]
494  */
495  void currentTransform(float xform[6]);
496 
497  /**
498  The following functions can be used to make calculations on 2x3 transformation matrices.
499  A 2x3 matrix is represented as float[6]. */
500 
501  /**
502  Sets the transform to identity matrix.
503  */
504  static void transformIdentity(float dst[6]);
505 
506  /**
507  Sets the transform to translation matrix
508  */
509  static void transformTranslate(float dst[6], float tx, float ty);
510 
511  /**
512  Sets the transform to scale matrix.
513  */
514  static void transformScale(float dst[6], float sx, float sy);
515 
516  /**
517  Sets the transform to rotate matrix. Angle is specified in radians.
518  */
519  static void transformRotate(float dst[6], float a);
520 
521  /**
522  Sets the transform to skew-x matrix. Angle is specified in radians.
523  */
524  static void transformSkewX(float dst[6], float a);
525 
526  /**
527  Sets the transform to skew-y matrix. Angle is specified in radians.
528  */
529  static void transformSkewY(float dst[6], float a);
530 
531  /**
532  Sets the transform to the result of multiplication of two transforms, of A = A*B.
533  */
534  static void transformMultiply(float dst[6], const float src[6]);
535 
536  /**
537  Sets the transform to the result of multiplication of two transforms, of A = B*A.
538  */
539  static void transformPremultiply(float dst[6], const float src[6]);
540 
541  /**
542  Sets the destination to inverse of specified transform.
543  Returns 1 if the inverse could be calculated, else 0.
544  */
545  static int transformInverse(float dst[6], const float src[6]);
546 
547  /**
548  Transform a point by given transform.
549  */
550  static void transformPoint(float& dstx, float& dsty, const float xform[6], float srcx, float srcy);
551 
552  /**
553  Convert degrees to radians.
554  */
555  static float degToRad(float deg);
556 
557  /**
558  Convert radians to degrees.
559  */
560  static float radToDeg(float rad);
561 
562  /* --------------------------------------------------------------------
563  * Images */
564 
565  /**
566  Creates image by loading it from the disk from specified file name.
567  */
568  NanoImage::Handle createImageFromFile(const char* filename, ImageFlags imageFlags);
569 
570  /**
571  Creates image by loading it from the disk from specified file name.
572  Overloaded function for convenience.
573  @see ImageFlags
574  */
575  NanoImage::Handle createImageFromFile(const char* filename, int imageFlags);
576 
577  /**
578  Creates image by loading it from the specified chunk of memory.
579  */
580  NanoImage::Handle createImageFromMemory(uchar* data, uint dataSize, ImageFlags imageFlags);
581 
582  /**
583  Creates image by loading it from the specified chunk of memory.
584  Overloaded function for convenience.
585  @see ImageFlags
586  */
587  NanoImage::Handle createImageFromMemory(uchar* data, uint dataSize, int imageFlags);
588 
589  /**
590  Creates image from specified raw format image data.
591  */
592  NanoImage::Handle createImageFromRawMemory(uint w, uint h, const uchar* data,
593  ImageFlags imageFlags, ImageFormat format);
594 
595  /**
596  Creates image from specified raw format image data.
597  Overloaded function for convenience.
598  @see ImageFlags
599  */
600  NanoImage::Handle createImageFromRawMemory(uint w, uint h, const uchar* data,
601  int imageFlags, ImageFormat format);
602 
603  /**
604  Creates image from specified RGBA image data.
605  */
606  NanoImage::Handle createImageFromRGBA(uint w, uint h, const uchar* data, ImageFlags imageFlags);
607 
608  /**
609  Creates image from specified RGBA image data.
610  Overloaded function for convenience.
611  @see ImageFlags
612  */
613  NanoImage::Handle createImageFromRGBA(uint w, uint h, const uchar* data, int imageFlags);
614 
615  /**
616  Creates image from an OpenGL texture handle.
617  */
618  NanoImage::Handle createImageFromTextureHandle(GLuint textureId, uint w, uint h, ImageFlags imageFlags, bool deleteTexture = false);
619 
620  /**
621  Creates image from an OpenGL texture handle.
622  Overloaded function for convenience.
623  @see ImageFlags
624  */
625  NanoImage::Handle createImageFromTextureHandle(GLuint textureId, uint w, uint h, int imageFlags, bool deleteTexture = false);
626 
627  /* --------------------------------------------------------------------
628  * Paints */
629 
630  /**
631  Creates and returns a linear gradient. Parameters (sx,sy)-(ex,ey) specify the start and end coordinates
632  of the linear gradient, icol specifies the start color and ocol the end color.
633  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
634  */
635  Paint linearGradient(float sx, float sy, float ex, float ey, const Color& icol, const Color& ocol);
636 
637  /**
638  Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering
639  drop shadows or highlights for boxes. Parameters (x,y) define the top-left corner of the rectangle,
640  (w,h) define the size of the rectangle, r defines the corner radius, and f feather. Feather defines how blurry
641  the border of the rectangle is. Parameter icol specifies the inner color and ocol the outer color of the gradient.
642  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
643  */
644  Paint boxGradient(float x, float y, float w, float h, float r, float f, const Color& icol, const Color& ocol);
645 
646  /**
647  Creates and returns a radial gradient. Parameters (cx,cy) specify the center, inr and outr specify
648  the inner and outer radius of the gradient, icol specifies the start color and ocol the end color.
649  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
650  */
651  Paint radialGradient(float cx, float cy, float inr, float outr, const Color& icol, const Color& ocol);
652 
653  /**
654  Creates and returns an image pattern. Parameters (ox,oy) specify the left-top location of the image pattern,
655  (ex,ey) the size of one image, angle rotation around the top-left corner, image is handle to the image to render.
656  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
657  */
658  Paint imagePattern(float ox, float oy, float ex, float ey, float angle, const NanoImage& image, float alpha);
659 
660  /* --------------------------------------------------------------------
661  * Scissoring */
662 
663  /**
664  Sets the current scissor rectangle.
665  The scissor rectangle is transformed by the current transform.
666  */
667  void scissor(float x, float y, float w, float h);
668 
669  /**
670  Intersects current scissor rectangle with the specified rectangle.
671  The scissor rectangle is transformed by the current transform.
672  Note: in case the rotation of previous scissor rect differs from
673  the current one, the intersection will be done between the specified
674  rectangle and the previous scissor rectangle transformed in the current
675  transform space. The resulting shape is always rectangle.
676  */
677  void intersectScissor(float x, float y, float w, float h);
678 
679  /**
680  Reset and disables scissoring.
681  */
682  void resetScissor();
683 
684  /* --------------------------------------------------------------------
685  * Paths */
686 
687  /**
688  Clears the current path and sub-paths.
689  */
690  void beginPath();
691 
692  /**
693  Starts new sub-path with specified point as first point.
694  */
695  void moveTo(float x, float y);
696 
697  /**
698  Adds line segment from the last point in the path to the specified point.
699  */
700  void lineTo(float x, float y);
701 
702  /**
703  Adds cubic bezier segment from last point in the path via two control points to the specified point.
704  */
705  void bezierTo(float c1x, float c1y, float c2x, float c2y, float x, float y);
706 
707  /**
708  Adds quadratic bezier segment from last point in the path via a control point to the specified point.
709  */
710  void quadTo(float cx, float cy, float x, float y);
711 
712  /**
713  Adds an arc segment at the corner defined by the last path point, and two specified points.
714  */
715  void arcTo(float x1, float y1, float x2, float y2, float radius);
716 
717  /**
718  Closes current sub-path with a line segment.
719  */
720  void closePath();
721 
722  /**
723  Sets the current sub-path winding.
724  */
725  void pathWinding(Winding dir);
726 
727  /**
728  Creates new circle arc shaped sub-path. The arc center is at cx,cy, the arc radius is r,
729  and the arc is drawn from angle a0 to a1, and swept in direction dir (NVG_CCW or NVG_CW).
730  Angles are specified in radians.
731  */
732  void arc(float cx, float cy, float r, float a0, float a1, Winding dir);
733 
734  /**
735  Creates new rectangle shaped sub-path.
736  */
737  void rect(float x, float y, float w, float h);
738 
739  /**
740  Creates new rounded rectangle shaped sub-path.
741  */
742  void roundedRect(float x, float y, float w, float h, float r);
743 
744  /**
745  Creates new ellipse shaped sub-path.
746  */
747  void ellipse(float cx, float cy, float rx, float ry);
748 
749  /**
750  Creates new circle shaped sub-path.
751  */
752  void circle(float cx, float cy, float r);
753 
754  /**
755  Fills the current path with current fill style.
756  */
757  void fill();
758 
759  /**
760  Fills the current path with current stroke style.
761  */
762  void stroke();
763 
764  /* --------------------------------------------------------------------
765  * Text */
766 
767  /**
768  Creates font by loading it from the disk from specified file name.
769  Returns handle to the font.
770  */
771  FontId createFontFromFile(const char* name, const char* filename);
772 
773  /**
774  Creates font by loading it from the specified memory chunk.
775  Returns handle to the font.
776  */
777  FontId createFontFromMemory(const char* name, const uchar* data, uint dataSize, bool freeData);
778 
779  /**
780  Finds a loaded font of specified name, and returns handle to it, or -1 if the font is not found.
781  */
782  FontId findFont(const char* name);
783 
784  /**
785  Sets the font size of current text style.
786  */
787  void fontSize(float size);
788 
789  /**
790  Sets the blur of current text style.
791  */
792  void fontBlur(float blur);
793 
794  /**
795  Sets the letter spacing of current text style.
796  */
797  void textLetterSpacing(float spacing);
798 
799  /**
800  Sets the proportional line height of current text style. The line height is specified as multiple of font size.
801  */
802  void textLineHeight(float lineHeight);
803 
804  /**
805  Sets the text align of current text style.
806  */
807  void textAlign(Align align);
808 
809  /**
810  Sets the text align of current text style.
811  Overloaded function for convenience.
812  @see Align
813  */
814  void textAlign(int align);
815 
816  /**
817  Sets the font face based on specified id of current text style.
818  */
819  void fontFaceId(FontId font);
820 
821  /**
822  Sets the font face based on specified name of current text style.
823  */
824  void fontFace(const char* font);
825 
826  /**
827  Draws text string at specified location. If end is specified only the sub-string up to the end is drawn.
828  */
829  float text(float x, float y, const char* string, const char* end);
830 
831  /**
832  Draws multi-line text string at specified location wrapped at the specified width.
833  If end is specified only the sub-string up to the end is drawn.
834  White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered.
835  Words longer than the max width are slit at nearest character (i.e. no hyphenation).
836  */
837  void textBox(float x, float y, float breakRowWidth, const char* string, const char* end = nullptr);
838 
839  /**
840  Measures the specified text string. The bounds value are [xmin,ymin, xmax,ymax].
841  Returns the horizontal advance of the measured text (i.e. where the next character should drawn).
842  Measured values are returned in local coordinate space.
843  */
844  float textBounds(float x, float y, const char* string, const char* end, Rectangle<float>& bounds);
845 
846  /**
847  Measures the specified multi-text string. Parameter bounds should be a pointer to float[4],
848  if the bounding box of the text should be returned. The bounds value are [xmin,ymin, xmax,ymax]
849  Measured values are returned in local coordinate space.
850  */
851  void textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end, float bounds[4]);
852 
853  /**
854  Calculates the glyph x positions of the specified text. If end is specified only the sub-string will be used.
855  Measured values are returned in local coordinate space.
856  */
857  int textGlyphPositions(float x, float y, const char* string, const char* end, GlyphPosition& positions, int maxPositions);
858 
859  /**
860  Returns the vertical metrics based on the current text style.
861  Measured values are returned in local coordinate space.
862  */
863  void textMetrics(float* ascender, float* descender, float* lineh);
864 
865  /**
866  Breaks the specified text into lines. If end is specified only the sub-string will be used.
867  White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered.
868  Words longer than the max width are slit at nearest character (i.e. no hyphenation).
869  */
870  int textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow& rows, int maxRows);
871 
872 #ifndef DGL_NO_SHARED_RESOURCES
873  /**
874  Load DPF's internal shared resources for this NanoVG class.
875  */
876  virtual bool loadSharedResources();
877 #endif
878 
879 private:
880  NVGcontext* const fContext;
881  bool fInFrame;
882  bool fIsSubWidget;
883 
884  DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoVG)
885 };
886 
887 // -----------------------------------------------------------------------
888 // NanoWidget
889 
890 /**
891  NanoVG Widget class.
892 
893  This class implements the NanoVG drawing API inside a DGL Widget.
894  The drawing function onDisplay() is implemented internally but a
895  new onNanoDisplay() needs to be overridden instead.
896  */
897 template <class BaseWidget>
898 class NanoBaseWidget : public BaseWidget,
899  public NanoVG
900 {
901 public:
902  /**
903  Constructor for a NanoSubWidget.
904  @see CreateFlags
905  */
906  explicit NanoBaseWidget(Widget* parentGroupWidget, int flags = CREATE_ANTIALIAS);
907 
908  /**
909  Constructor for a NanoTopLevelWidget.
910  @see CreateFlags
911  */
912  explicit NanoBaseWidget(Window& windowToMapTo, int flags = CREATE_ANTIALIAS);
913 
914  /**
915  Constructor for a NanoStandaloneWindow without transient parent window.
916  @see CreateFlags
917  */
918  explicit NanoBaseWidget(Application& app, int flags = CREATE_ANTIALIAS);
919 
920  /**
921  Constructor for a NanoStandaloneWindow with transient parent window.
922  @see CreateFlags
923  */
924  explicit NanoBaseWidget(Application& app, Window& transientParentWindow, int flags = CREATE_ANTIALIAS);
925 
926  /**
927  Destructor.
928  */
929  virtual ~NanoBaseWidget() {}
930 
931 protected:
932  /**
933  New virtual onDisplay function.
934  @see onDisplay
935  */
936  virtual void onNanoDisplay() = 0;
937 
938 private:
939  /**
940  Widget display function.
941  Implemented internally to wrap begin/endFrame() automatically.
942  */
943  inline void onDisplay() override
944  {
945  // NOTE maybe should use BaseWidget::getWindow().getScaleFactor() as 3rd arg ?
946  NanoVG::beginFrame(BaseWidget::getWidth(), BaseWidget::getHeight());
947  onNanoDisplay();
949  }
950 
951  // these should not be used
952  void beginFrame(uint,uint) {}
953  void beginFrame(uint,uint,float) {}
954  void beginFrame(Widget*) {}
955  void cancelFrame() {}
956  void endFrame() {}
957 
958  DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoBaseWidget)
959 };
960 
964 
965 DISTRHO_DEPRECATED_BY("NanoSubWidget")
966 typedef NanoSubWidget NanoWidget;
967 
968 // -----------------------------------------------------------------------
969 
970 END_NAMESPACE_DGL
971 
972 #ifdef _MSC_VER
973 # pragma warning(pop)
974 #endif
975 
976 #endif // DGL_NANO_WIDGET_HPP_INCLUDED
NanoVG::CREATE_ANTIALIAS
@ CREATE_ANTIALIAS
Definition: NanoVG.hpp:219
NanoVG::rotate
void rotate(float angle)
NanoVG::boxGradient
Paint boxGradient(float x, float y, float w, float h, float r, float f, const Color &icol, const Color &ocol)
NanoImage::getTextureHandle
GLuint getTextureHandle() const
NanoVG::skewX
void skewX(float angle)
NanoVG::stroke
void stroke()
NanoVG::radToDeg
static float radToDeg(float rad)
NanoVG::transformMultiply
static void transformMultiply(float dst[6], const float src[6])
NanoVG::currentTransform
void currentTransform(float xform[6])
NanoVG::skewY
void skewY(float angle)
NanoVG::createImageFromRawMemory
NanoImage::Handle createImageFromRawMemory(uint w, uint h, const uchar *data, ImageFlags imageFlags, ImageFormat format)
NanoVG::CREATE_STENCIL_STROKES
@ CREATE_STENCIL_STROKES
Definition: NanoVG.hpp:225
NanoVG::textGlyphPositions
int textGlyphPositions(float x, float y, const char *string, const char *end, GlyphPosition &positions, int maxPositions)
NanoBaseWidget
Definition: NanoVG.hpp:898
NanoVG::beginPath
void beginPath()
NanoVG::degToRad
static float degToRad(float deg)
NanoVG::roundedRect
void roundedRect(float x, float y, float w, float h, float r)
NanoVG::textLineHeight
void textLineHeight(float lineHeight)
NanoVG::transformPremultiply
static void transformPremultiply(float dst[6], const float src[6])
NanoVG::transformInverse
static int transformInverse(float dst[6], const float src[6])
NanoVG::resetTransform
void resetTransform()
NanoVG::TextRow
Definition: NanoVG.hpp:295
Window
Definition: Window.hpp:50
NanoVG::rect
void rect(float x, float y, float w, float h)
NanoVG::radialGradient
Paint radialGradient(float cx, float cy, float inr, float outr, const Color &icol, const Color &ocol)
NanoVG::createImageFromRGBA
NanoImage::Handle createImageFromRGBA(uint w, uint h, const uchar *data, ImageFlags imageFlags)
NanoVG::fillColor
void fillColor(const Color &color)
NanoImage::~NanoImage
~NanoImage()
NanoVG::scissor
void scissor(float x, float y, float w, float h)
NanoVG::fontFaceId
void fontFaceId(FontId font)
NanoVG::lineCap
void lineCap(LineCap cap=BUTT)
Size< uint >
Rectangle
Definition: Geometry.hpp:30
Application
Definition: Application.hpp:36
NanoVG::fontSize
void fontSize(float size)
NanoVG::strokeColor
void strokeColor(const Color &color)
NanoVG::loadSharedResources
virtual bool loadSharedResources()
NanoImage
Definition: NanoVG.hpp:54
NanoVG::lineJoin
void lineJoin(LineCap join=MITER)
NanoVG::miterLimit
void miterLimit(float limit)
NanoVG::quadTo
void quadTo(float cx, float cy, float x, float y)
NanoVG::translate
void translate(float x, float y)
NanoVG::scale
void scale(float x, float y)
NanoVG::linearGradient
Paint linearGradient(float sx, float sy, float ex, float ey, const Color &icol, const Color &ocol)
NanoVG::transformSkewX
static void transformSkewX(float dst[6], float a)
NanoVG::fontBlur
void fontBlur(float blur)
NanoVG::CreateFlags
CreateFlags
Definition: NanoVG.hpp:215
NanoVG::pathWinding
void pathWinding(Winding dir)
NanoVG::transform
void transform(float a, float b, float c, float d, float e, float f)
NanoVG::endFrame
void endFrame()
NanoVG::GlyphPosition
Definition: NanoVG.hpp:289
NanoVG::fillPaint
void fillPaint(const Paint &paint)
NanoVG::getContext
NVGcontext * getContext() const noexcept
Definition: NanoVG.hpp:327
NanoVG::transformRotate
static void transformRotate(float dst[6], float a)
NanoVG::beginFrame
void beginFrame(const uint width, const uint height, const float scaleFactor=1.0f)
NanoVG::strokePaint
void strokePaint(const Paint &paint)
NanoVG::createImageFromFile
NanoImage::Handle createImageFromFile(const char *filename, ImageFlags imageFlags)
NanoBaseWidget::NanoBaseWidget
NanoBaseWidget(Widget *parentGroupWidget, int flags=CREATE_ANTIALIAS)
NanoVG::imagePattern
Paint imagePattern(float ox, float oy, float ex, float ey, float angle, const NanoImage &image, float alpha)
NanoVG::save
void save()
NanoVG::Paint
Definition: NanoVG.hpp:271
NanoVG::textBounds
float textBounds(float x, float y, const char *string, const char *end, Rectangle< float > &bounds)
NanoVG::lineTo
void lineTo(float x, float y)
NanoVG::globalAlpha
void globalAlpha(float alpha)
NanoVG::transformIdentity
static void transformIdentity(float dst[6])
NanoVG::transformSkewY
static void transformSkewY(float dst[6], float a)
NanoVG::resetScissor
void resetScissor()
NanoVG::createImageFromTextureHandle
NanoImage::Handle createImageFromTextureHandle(GLuint textureId, uint w, uint h, ImageFlags imageFlags, bool deleteTexture=false)
NanoVG::createImageFromMemory
NanoImage::Handle createImageFromMemory(uchar *data, uint dataSize, ImageFlags imageFlags)
NanoVG::textBox
void textBox(float x, float y, float breakRowWidth, const char *string, const char *end=nullptr)
NanoVG::fontFace
void fontFace(const char *font)
NanoImage::operator=
NanoImage & operator=(const Handle &handle)
NanoVG::transformPoint
static void transformPoint(float &dstx, float &dsty, const float xform[6], float srcx, float srcy)
NanoVG::restore
void restore()
NanoVG::createFontFromFile
FontId createFontFromFile(const char *name, const char *filename)
NanoVG::transformScale
static void transformScale(float dst[6], float sx, float sy)
NanoVG::CREATE_DEBUG
@ CREATE_DEBUG
Definition: NanoVG.hpp:230
NanoVG::textBreakLines
int textBreakLines(const char *string, const char *end, float breakRowWidth, TextRow &rows, int maxRows)
NanoVG::circle
void circle(float cx, float cy, float r)
NanoVG::arc
void arc(float cx, float cy, float r, float a0, float a1, Winding dir)
NanoVG::createFontFromMemory
FontId createFontFromMemory(const char *name, const uchar *data, uint dataSize, bool freeData)
NanoVG::closePath
void closePath()
NanoVG::strokeWidth
void strokeWidth(float size)
NanoVG::intersectScissor
void intersectScissor(float x, float y, float w, float h)
NanoBaseWidget::onNanoDisplay
virtual void onNanoDisplay()=0
NanoImage::isValid
bool isValid() const noexcept
NanoVG::transformTranslate
static void transformTranslate(float dst[6], float tx, float ty)
NanoVG::textBoxBounds
void textBoxBounds(float x, float y, float breakRowWidth, const char *string, const char *end, float bounds[4])
NanoBaseWidget::~NanoBaseWidget
virtual ~NanoBaseWidget()
Definition: NanoVG.hpp:929
NanoVG::moveTo
void moveTo(float x, float y)
NanoVG::cancelFrame
void cancelFrame()
NanoVG::ellipse
void ellipse(float cx, float cy, float rx, float ry)
NanoVG::text
float text(float x, float y, const char *string, const char *end)
NanoVG::arcTo
void arcTo(float x1, float y1, float x2, float y2, float radius)
NanoVG
Definition: NanoVG.hpp:212
NanoVG::reset
void reset()
NanoVG::fill
void fill()
NanoVG::textLetterSpacing
void textLetterSpacing(float spacing)
NanoVG::NanoVG
NanoVG(int flags=CREATE_ANTIALIAS)
NanoVG::findFont
FontId findFont(const char *name)
NanoVG::textMetrics
void textMetrics(float *ascender, float *descender, float *lineh)
NanoVG::textAlign
void textAlign(Align align)
NanoVG::~NanoVG
virtual ~NanoVG()
Color
Definition: Color.hpp:31
NanoImage::getSize
Size< uint > getSize() const noexcept
NanoImage::NanoImage
NanoImage()
NanoVG::bezierTo
void bezierTo(float c1x, float c1y, float c2x, float c2y, float x, float y)
Widget
Definition: Widget.hpp:53