Functions to create and destory NanoVega context.
Pointer to opaque NanoVega context structure.
Context creation flags.
valid only inside beginFrame/endFrame
Returns flags for glClear().
valid only inside beginFrame/endFrame
Returns true if beginFrame was called, and neither endFrame, nor cancelFrame were.
Delete NanoVega context.
Creates NanoVega contexts for OpenGL2+.
>=0: this pickid will be assigned to all filled/stroked paths
>=0: this pickid will be assigned to all filled/stroked paths
pick autoregistration mode; see NVGPickKind
pick autoregistration mode; see NVGPickKind
Get current Bezier tesselation mode. See NVGTesselation.
Set current Bezier tesselation mode. See NVGTesselation.
Returns true if the given context is not null and can be used for painting.
valid only inside beginFrame/endFrame
To start drawing with NanoVega context, you have to "begin frame", and then "end frame" to flush your rendering commands to GPU.
Begin drawing a new frame.
Cancels drawing the current frame. Cancels path recording.
Ends drawing the current frame (flushing remaining render state). Commits recorded paths.
The composite operations in NanoVega are modeled after HTML Canvas API, and the blend func is based on OpenGL (see corresponding manuals for more info). The colors in the blending state have premultiplied alpha.
Blending type.
Composite operation (HTML5-alike).
Sets the composite operation with custom pixel arithmetic.
Sets the composite operation with custom pixel arithmetic for RGB and alpha components separately.
Sets the composite operation.
Composite operation state.
Colors in NanoVega are stored as ARGB. Zero alpha means "transparent color".
Returns color value specified by hue, saturation and lightness. HSL values are all in range [0..1], alpha will be set to 255.
Returns color value specified by hue, saturation and lightness and alpha. HSL values are all in range [0..1], alpha in range [0..255].
Returns color value specified by hue, saturation and lightness and alpha. HSL values and alpha are all in range [0..1].
Linearly interpolates from color c0 to c1, and returns resulting color value.
Returns a color value from string form. Supports: "#rgb", "#rrggbb", "#argb", "#aarrggbb"
Returns a color value from red, green, blue values. Alpha will be set to 255 (1.0f).
Returns a color value from string form. Supports: "#rgb", "#rrggbb", "#argb", "#aarrggbb"
Returns a color value from red, green, blue and alpha values.
Returns a color value from red, green, blue and alpha values.
Returns a color value from red, green, blue values. Alpha will be set to 1.0f.
Returns new color with transparency (alpha) set to a.
The paths, gradients, patterns and scissor region are transformed by an transformation matrix at the time when they are passed to the API. The current transformation matrix is an affine matrix:
[sx kx tx] [ky sy ty] [ 0 0 1]
Where: (sx, sy) define scaling, (kx, ky) skewing, and (tx, ty) translation. The last row is assumed to be (0, 0, 1) and is not stored.
Apart from resetTransform, each transformation function first creates specific transformation matrix and pre-multiplies the current transformation by it.
Current coordinate system (transformation) can be saved and restored using save and restore.
The following functions can be used to make calculations on 2x3 transformation matrices. A 2x3 matrix is represented as float[6].
Converts degrees to radians.
Converts radians to degrees.
Matrix class.
NanoVega contains state which represents how paths will be rendered. The state contains transform, fill and stroke styles, text and font styles, and scissor clipping.
Returns true if we have any saved state.
Returns true if we have any room in state stack. It is guaranteed to have at least 32 stack slots.
Returns true if rendering is currently blocked.
Blocks/unblocks rendering
Resets current render state to default values. Does not affect the render state stack.
Pops and restores current render state.
Pushes and saves the current render state into a state stack. A matching restore must be used to restore the state. Returns false if state stack overflowed.
Blocks/unblocks rendering; returns previous state.
Fill and stroke render style can be either a solid color or a paint which is a gradient or a pattern. Solid color is simply defined as a color value, different kinds of paints can be created using linearGradient, boxGradient, radialGradient and imagePattern.
Current render style can be saved and restored using save and restore.
Note that if you want "almost perfect" pixel rendering, you should set aspect ratio to 1, and use integerCoord+0.5f as pixel coordinates.
Line cap style.
Sets filling mode to "even-odd".
Sets current fill style to a solid color.
Sets current fill style to a solid color.
Sets current fill style to a paint, which can be a one of the gradients or a pattern.
Sets current fill style to a multistop linear gradient.
Sets the transparency applied to all rendered shapes. Already transparent paths will get proportionally more transparent as well.
Sets how the end of the line (cap) is drawn, Can be one of: NVGLineCap.Butt (default), NVGLineCap.Round, NVGLineCap.Square.
Sets how sharp path corners are drawn. Can be one of NVGLineCap.Miter (default), NVGLineCap.Round, NVGLineCap.Bevel.
Sets the miter limit of the stroke style. Miter limit controls when a sharp corner is beveled.
Sets filling mode to "non-zero" (this is default mode).
Sets stroke dashing, using (dash_length, gap_length) pairs. Current limit is 16 pairs. Resets dash start to zero.
Sets stroke dashing, using (dash_length, gap_length) pairs. Current limit is 16 pairs.
Sets current stroke style to a solid color.
Sets current stroke style to a solid color.
Sets current stroke style to a paint, which can be a one of the gradients or a pattern.
Sets the stroke width of the stroke style.
Paint parameters for various fills. Don't change anything here!
Transformation matrix management for the current rendering style. Transformations are applied in backwards order. I.e. if you first translate, and then rotate, your path will be rotated around it's origin, and then translated to the destination point.
Returns current transformation matrix.
Sets current transformation matrix.
Resets current transform to an identity matrix.
Rotates current coordinate system. Angle is specified in radians.
Scales the current coordinate system.
Skews the current coordinate system along X axis. Angle is specified in radians.
Skews the current coordinate system along Y axis. Angle is specified in radians.
Premultiplies current coordinate system by specified matrix.
Translates current coordinate system.
Scissoring allows you to clip the rendering into a rectangle. This is useful for various user interface cases like rendering a text edit or a timeline.
Intersects current scissor rectangle with the specified rectangle. The scissor rectangle is transformed by the current transform. Note: in case the rotation of previous scissor rect differs from the current one, the intersection will be done between the specified rectangle and the previous scissor rectangle transformed in the current transform space. The resulting shape is always rectangle.
Intersects current scissor rectangle with the specified rectangle. The scissor rectangle is transformed by the current transform. Note: in case the rotation of previous scissor rect differs from the current one, the intersection will be done between the specified rectangle and the previous scissor rectangle transformed in the current transform space. The resulting shape is always rectangle.
Reset and disables scissoring.
Sets the current scissor rectangle. The scissor rectangle is transformed by the current transform.
Sets the current scissor rectangle. The scissor rectangle is transformed by the current transform. Arguments: [x, y, w, h]*
NanoVega allows you to load image files in various formats (if arsd loaders are in place) to be used for rendering. In addition you can upload your own image. The parameter imageFlagsList is a list of flags defined in NVGImageFlag.
If you will use your image as fill pattern, it will be scaled by default. To make it repeat, pass NVGImageFlag.RepeatX and NVGImageFlag.RepeatY flags to image creation function respectively.
Image creation flags.
Creates image by loading it from the disk from specified file name. Returns handle to the image or 0 on error.
Creates image by loading it from the specified memory image. Returns handle to the image or 0 on error.
Creates image by loading it from the specified chunk of memory. Returns handle to the image or 0 on error.
Creates image from specified image data. Returns handle to the image or 0 on error.
Deletes created image.
Using OpenGL texture id creates GLNVGtexture and return its id.
Create NVGImage from OpenGL texture id.
Returns OpenGL texture id for NanoVega image.
Returns the dimensions of a created image.
Updates image data specified by image handle.
NanoVega image handle.
NanoVega supports four types of paints: linear gradient, box gradient, radial gradient and image pattern. These can be used as paints for strokes and fills.
Returns NVGPaint for linear gradient with stops, created with createLinearGradientWithStops. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.
Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering drop shadows or highlights for boxes. Parameters (x, y) define the top-left corner of the rectangle, (w, h) define the size of the rectangle, r defines the corner radius, and f feather. Feather defines how blurry the border of the rectangle is. Parameter icol specifies the inner color and ocol the outer color of the gradient. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.
Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering drop shadows or highlights for boxes. Parameters (x, y) define the top-left corner of the rectangle, (w, h) define the size of the rectangle, r defines the corner radius, and f feather. Feather defines how blurry the border of the rectangle is. Parameter icol specifies the inner color and ocol the outer color of the gradient. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.
Create linear gradient data suitable to use with linearGradient(res). Don't forget to destroy the result when you don't need it anymore with ctx.kill(res);.
Creates and returns an image pattern. Parameters (cx, cy) specify the left-top location of the image pattern, (w, h) the size of one image, angle rotation around the top-left corner, image is handle to the image to render. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.
Creates and returns a linear gradient. Parameters (sx, sy) (ex, ey) specify the start and end coordinates of the linear gradient, icol specifies the start color and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.
Creates and returns a linear gradient with middle stop. Parameters (sx, sy) (ex, ey) specify the start and end coordinates of the linear gradient, icol specifies the start color, midp specifies stop point in range (0..1), and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.
Creates and returns a linear gradient. Parameters (sx, sy) (ex, ey) specify the start and end coordinates of the linear gradient, icol specifies the start color and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.
Creates and returns a linear gradient with middle stop. Parameters (sx, sy) (ex, ey) specify the start and end coordinates of the linear gradient, icol specifies the start color, midp specifies stop point in range (0..1), and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.
Creates and returns a radial gradient. Parameters (cx, cy) specify the center, inr and outr specify the inner and outer radius of the gradient, icol specifies the start color and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.
Creates and returns a radial gradient. Parameters (cx, cy) specify the center, inr and outr specify the inner and outer radius of the gradient, icol specifies the start color and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.
Gradient Stop Point.
Linear gradient with multiple stops.
It is possible to set affine transformation matrix for GPU. That matrix will be applied by the shader code. This can be used to quickly translate and rotate saved paths. Call this only between beginFrame and endFrame.
Note that beginFrame resets this matrix to identity one.
Sets GPU affine transformatin matrix. Don't do scaling or skewing here. This matrix won't be saved/restored with context state save/restore operations, as it is not a part of that state.
Get current GPU affine transformatin matrix.
"Untransform" point using current GPU affine matrix.
Drawing a new shape starts with beginPath, it clears all the currently defined paths. Then you define one or more paths and sub-paths which describe the shape. The are functions to draw common shapes like rectangles and circles, and lower level step-by-step functions, which allow to define a path curve by curve.
NanoVega uses even-odd fill rule to draw the shapes. Solid shapes should have counter clockwise winding and holes should have counter clockwise order. To specify winding of a path you can call pathWinding. This is useful especially for the common shapes, which are drawn CCW.
Finally you can fill the path using current fill style by calling fill, and stroke it with current stroke style by calling stroke.
The curve segments and sub-paths are transformed by the current transform.
Path solidity.
Path winding.
Creates new circle arc shaped sub-path. The arc center is at (cx, cy), the arc radius is r, and the arc is drawn from angle a0 to a1, and swept in direction dir (NVGWinding.CCW, or NVGWinding.CW). Angles are specified in radians.
Creates new circle arc shaped sub-path. The arc center is at (cx, cy), the arc radius is r, and the arc is drawn from angle a0 to a1, and swept in direction dir (NVGWinding.CCW, or NVGWinding.CW). Angles are specified in radians.
Adds an arc segment at the corner defined by the last path point, and two specified points.
Adds an arc segment at the corner defined by the last path point, and two specified points. Arguments: [x1, y1, x2, y2, radius]*
Clears the current path and sub-paths.
Adds cubic bezier segment from last point in the path via two control points to the specified point.
Adds cubic bezier segment from last point in the path via two control points to the specified point. Arguments: [c1x, c1y, c2x, c2y, x, y]*
Creates new circle shaped sub-path.
Creates new circle shaped sub-path. Arguments: [cx, cy, r]*
Closes current sub-path with a line segment.
Creates new ellipse shaped sub-path.
Creates new ellipse shaped sub-path. Arguments: [cx, cy, rx, ry]*
Fills the current path with current fill style.
Return outline of the current path. Returned outline is not flattened.
Adds line segment from the last point in the path to the specified point.
Adds line segment from the last point in the path to the specified point. Arguments: [x, y]*
Starts new sub-path with specified point as first point.
Starts new sub-path with specified point as first point. Arguments: [x, y]*
Sets the current sub-path winding, see NVGWinding and NVGSolidity.
Adds quadratic bezier segment from last point in the path via a control point to the specified point.
Adds quadratic bezier segment from last point in the path via a control point to the specified point. Arguments: [cx, cy, x, y]*
Creates new rectangle shaped sub-path. Arguments: [x, y, w, h]*
Creates new rectangle shaped sub-path.
Creates new rounded rectangle shaped sub-path.
Creates new rounded rectangle shaped sub-path. Arguments: [x, y, w, h, radius]*
Creates new rounded rectangle shaped sub-path. Specify ellipse width and height to round corners according to it.
Creates new rounded rectangle shaped sub-path. Specify ellipse width and height to round corners according to it. Arguments: [x, y, w, h, rw, rh]*
Creates new rounded rectangle shaped sub-path. This one allows you to specify different rounding radii for each corner. Arguments: [x, y, w, h, radTopLeft, radTopRight, radBottomRight, radBottomLeft]*
Creates new rounded rectangle shaped sub-path. This one allows you to specify different rounding radii for each corner.
Fills the current path with current stroke style.
This is picking API that works directly on paths, without rasterizing them first.
beginFrame resets picking state. Then you can create paths as usual, but there is a possibility to perform hit checks before rasterizing a path. Call either id assigning functions (currFillHitId/currStrokeHitId), or immediate hit test functions (hitTestCurrFill/hitTestCurrStroke) before rasterizing (i.e. calling fill or stroke) to perform hover effects, for example.
Also note that picking API is ignoring GPU affine transformation matrix. You can "untransform" picking coordinates before checking with gpuUntransformPoint.
Pick type query. Used in hitTest and hitTestAll.
Marks the fill of the current path as pickable with the specified id. Note that you can create and mark path without rasterizing it.
Marks the stroke of the current path as pickable with the specified id. Note that you can create and mark path without rasterizing it.
Returns the id of the pickable shape containing x,y or NVGNoPick if no shape was found.
Fills ids with a list of the top most hit ids (from bottom to top) under the specified position. Returns the slice of ids.
Returns true if the given point is within the fill of the currently defined path. This operation can be done before rasterizing the current path.
Returns true if the given point is within the stroke of the currently defined path. This operation can be done before rasterizing the current path.
Returns true if the path with the given id contains x,y.
If scissoring is not enough for you, you can clip rendering with arbitrary path, or with combination of paths. Clip region is saved by save and restored by restore NanoVega functions. You can combine clip paths with various logic operations, see NVGClipMode.
Note that both clip and clipStroke are ignoring scissoring (i.e. clip mask is created as if there was no scissor set). Actual rendering is affected by scissors, though.
Sets current path as clipping region.
Mask combining more
Sets current path as clipping region.
Sets current path' stroke as clipping region.
NanoVega allows you to load .ttf files and use the font to render text. You have to load some font, and set proper font size before doing anything with text, as there is no "default" font provided by NanoVega. Also, don't forget to check return value of createFont(), 'cause NanoVega won't fail if it cannot load font, it will silently try to render nothing.
The appearance of the text can be defined by setting the current text style and by specifying the fill color. Common text and font settings such as font size, letter spacing and text align are supported. Font blur allows you to create simple text effects such as drop shadows.
At render time the font face can be set based on the font handles or name.
// in initialization: auto font = ctx.createFont("Roboto", "fonts/Roboto.ttf"); enforce(font != -1, "Failed to load font!"); foreach (fallbackPath; ["fonts/NotoSans.ttf"]) { auto fallback = ctx.createFont("fallback", fallbackPath); if (fallback == -1) { stderr.writeln("Failed to load fallback font ", fallbackPath); continue; } ctx.addFallbackFont(font, fallback); } // rendering: ctx.fontFaceId = font; //ctx.fontBlur = 3; //ctx.textAlign = NVGTextAlign.H.Center; ctx.fontSize = 20; ctx.fillColor = NVGColor.white; ctx.text(0, height, text);
Font measure functions return values in local space, the calculations are carried in the same resolution as the final rendering. This is done because the text glyph positions are snapped to the nearest pixels sharp rendering.
The local space means that values are not rotated or scale as per the current transformation. For example if you set font size to 12, which would mean that line height is 16, then regardless of the current scaling and rotation, the returned line height is always 16. Some measures may vary because of the scaling since aforementioned pixel snapping.
While this may sound a little odd, the setup allows you to always render the same way regardless of scaling. I.e. following works regardless of scaling:
string txt = "Text me up."; vg.textBounds(x, y, txt, bounds); vg.beginPath(); vg.roundedRect(bounds[0], bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1], 6); vg.fill();
Note: currently only solid color fill is supported for text.
Add fonts from another context. This is more effective than reloading fonts, 'cause font data will be shared.
Returns glyph outlines as array of commands. Vertical 0 is baseline. The glyph is not scaled in any way, so you have to use NanoVega transformations instead. Returns null if there is no such glyph, or current font is not scalable.
Returns bounds of the glyph outlines. Vertical 0 is baseline. The glyph is not scaled in any way. Returns false if there is no such glyph, or current font is not scalable.
Adds glyph outlines to the current path. Vertical 0 is baseline. The glyph is not scaled in any way, so you have to use NanoVega transformations instead. Returns false if there is no such glyph, or current font is not scalable.
Creates font by loading it from the disk from specified file name. Returns handle to the font or FONS_INVALID (aka -1) on error. Use "fontname:noaa" as name to turn off antialiasing (if font driver supports that).
Creates font by loading it from the specified memory chunk. Returns handle to the font or FONS_INVALID (aka -1) on error. Won't free data on error.
Finds a loaded font of specified name, and returns handle to it, or FONS_INVALID (aka -1) if the font is not found.
Gets the blur of current text style.
Sets the blur of current text style.
Sets the font face based on specified name of current text style.
Sets the font face based on specified id of current text style.
Gets the font face based on specified id of current text style.
Sets the font size of current text style.
Gets the font size of current text style.
Destroy glyph outiline and free allocated memory.
Draws text string at specified location. Returns next x position.
Sets the text align of current text style, see NVGTextAlign for options.
Gets the text align of current text style, see NVGTextAlign for options.
Measures the specified text string. Parameter bounds should be a float[4], if the bounding box of the text should be returned. The bounds value are [xmin, ymin, xmax, ymax] Returns the horizontal advance of the measured text (i.e. where the next character should drawn). Measured values are returned in local coordinate space.
Draws multi-line text string at specified location wrapped at the specified width. White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered. Words longer than the max width are slit at nearest character (i.e. no hyphenation).
Measures the specified text string. Parameter bounds should be a float[4], if the bounding box of the text should be returned. The bounds value are [xmin, ymin, xmax, ymax] Returns the horizontal advance of the measured text (i.e. where the next character should drawn). Measured values are returned in local coordinate space.
Breaks the specified text into lines. White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered. Words longer than the max width are slit at nearest character (i.e. no hyphenation). Returns number of rows.
Breaks the specified text into lines. White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered. Words longer than the max width are slit at nearest character (i.e. no hyphenation).
Measures the specified text string. Returns horizontal and vertical sizes of the measured text. Measured values are returned in local coordinate space.
Returns font ascender (positive), measured in local coordinate space.
Returns font descender (negative), measured in local coordinate space.
Returns font line height (without line spacing), measured in local coordinate space.
Calculates the glyph x positions of the specified text. Measured values are returned in local coordinate space.
Gets the letter spacing of current text style.
Sets the letter spacing of current text style.
Sets the proportional line height of current text style. The line height is specified as multiple of font size.
Gets the proportional line height of current text style. The line height is specified as multiple of font size.
Returns the vertical metrics based on the current text style. Measured values are returned in local coordinate space.
Measures the specified text string. Returns horizontal size of the measured text. Measured values are returned in local coordinate space.
Glyph position info.
charOutline will return NVGPathOutline.
Text align.
Text row storage.
Returns iterator which you can use to calculate text bounds and advancement. This is usable when you need to do some text layouting with wrapping, to avoid guesswork ("will advancement for this space stay the same?"), and Schlemiel's algorithm. Note that you can copy the returned struct to save iterator state.
FontStash is used to load fonts, to manage font atlases, and to get various text metrics. You don't need any graphics context to use FontStash, so you can do things like text layouting outside of your rendering code. Loaded fonts are refcounted, so it is cheap to create new FontStash, copy fonts from NanoVega context into it, and use that new FontStash to do some UI layouting, for example. Also note that you can get text metrics without creating glyph bitmaps (by using FONSTextBoundsIterator, for example); this way you don't need to waste CPU and memory resources to render unneeded images into font atlas, and you can layout alot of text very fast.
Note that "FontStash" is abbrevated as "FONS". So when you see some API that contains word "fons" in it, this is not a typo, and it should not read "font" intead.
TODO for Ketmar: write some nice example code here, and finish documenting FontStash API.
FontStash context
Returns FontStash context of the given NanoVega context.
Returns scale that should be applied to FontStash parameters due to matrix transformations on the context (or 1)
Free all resources used by the stash, and stash itself.
Setup NanoVega context font parameters from the given FontStash. Note that NanoVega can apply transformation scale later. Returns false if FontStash or NanoVega context is not active.
Setup FontStash from the given NanoVega context font parameters. Note that this will apply transformation scale too. Returns false if FontStash or NanoVega context is not active.
Invald font id.
Initial parameters for new FontStash.
This iterator can be used to do text measurement.
FontStash context (internal definition). Don't use it derectly, it was made public only to generate documentation.
A SimpleWindow subclass that encapsulates some nanovega defaults. You just set a redrawNVGScene delegate and, optionally, your normal event handlers for simpledisplay, and the rest is set up for you.
Bezier curve rasterizer.
Adds the font with id fallback onto the font with id base for characters that are not found in base's character set. May be called multiple times, up to an internal maximum count per font. Group: text_api
this is branchless for ints on x86, and even for longs on x86_64
Returns "complex path" flag for the given render path.
Returns number of tesselated pathes in context.
Get vertices of "fill" triangle fan for the given render path. Can return empty slice.
Get vertices of "stroke" triangle strip for the given render path. Can return empty slice.
Returns winding for the given render path.
Length proportional to radius of a cubic bezier handle for 90deg arcs.
Annotation to indicate the marked function is compatible with arsd.script.
Default tesselator for Bezier curves.
General NanoVega vertex struct. Contains geometry coordinates, and (sometimes unused) texture coordinates.
The drawing context is created using platform specific constructor function.
NVGContext vg = nvgCreateContext();
Drawing a simple shape using NanoVega consists of four steps:
vg.beginPath(); vg.rect(100, 100, 120, 30); vg.fillColor(nvgRGBA(255, 192, 0, 255)); vg.fill();
Calling beginPath will clear any existing paths and start drawing from blank slate. There are number of number of functions to define the path to draw, such as rectangle, rounded rectangle and ellipse, or you can use the common moveTo, lineTo, bezierTo and arcTo API to compose the paths step by step.
Because of the way the rendering backend is built in NanoVega, drawing a composite path, that is path consisting from multiple paths defining holes and fills, is a bit more involved. NanoVega uses non-zero filling rule and by default, and paths are wound in counter clockwise order. Keep that in mind when drawing using the low level draw API. In order to wind one of the predefined shapes as a hole, you should call pathWinding(NVGSolidity.Hole), or pathWinding(NVGSolidity.Solid) after defining the path.
vg.beginPath(); vg.rect(100, 100, 120, 30); vg.circle(120, 120, 5); vg.pathWinding(NVGSolidity.Hole); // mark circle as a hole vg.fillColor(nvgRGBA(255, 192, 0, 255)); vg.fill();
The OpenGL back-end touches following states:
When textures are uploaded or updated, the following pixel store is set to defaults: GL_UNPACK_ALIGNMENT, GL_UNPACK_ROW_LENGTH, GL_UNPACK_SKIP_PIXELS, GL_UNPACK_SKIP_ROWS. Texture binding is also affected. Texture updates can happen when the user loads images, or when new font glyphs are added. Glyphs are added as needed between calls to beginFrame and endFrame.
The data for the whole frame is buffered and flushed in endFrame. The following code illustrates the OpenGL state touched by the rendering code:
glUseProgram(prog); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CCW); glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); glDisable(GL_COLOR_LOGIC_OP); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glStencilMask(0xffffffff); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glStencilFunc(GL_ALWAYS, 0, 0xffffffff); glActiveTexture(GL_TEXTURE1); glActiveTexture(GL_TEXTURE0); glBindBuffer(GL_UNIFORM_BUFFER, buf); glBindVertexArray(arr); glBindBuffer(GL_ARRAY_BUFFER, buf); glBindTexture(GL_TEXTURE_2D, tex); glUniformBlockBinding(... , GLNVG_FRAG_BINDING);
This example shows how to do the NanoVega sample without the NVGWindow helper class.
1 import arsd.simpledisplay; 2 3 import arsd.nanovega; 4 5 void main () { 6 NVGContext nvg; // our NanoVega context 7 8 // we need at least OpenGL3 with GLSL to use NanoVega, 9 // so let's tell simpledisplay about that 10 setOpenGLContextVersion(3, 0); 11 12 // now create OpenGL window 13 auto sdmain = new SimpleWindow(800, 600, "NanoVega Simple Sample", OpenGlOptions.yes, Resizability.allowResizing); 14 15 // we need to destroy NanoVega context on window close 16 // stricly speaking, it is not necessary, as nothing fatal 17 // will happen if you'll forget it, but let's be polite. 18 // note that we cannot do that *after* our window was closed, 19 // as we need alive OpenGL context to do proper cleanup. 20 sdmain.onClosing = delegate () { 21 nvg.kill(); 22 }; 23 24 // this is called just before our window will be shown for the first time. 25 // we must create NanoVega context here, as it needs to initialize 26 // internal OpenGL subsystem with valid OpenGL context. 27 sdmain.visibleForTheFirstTime = delegate () { 28 // yes, that's all 29 sdmain.setAsCurrentOpenGlContext(); 30 nvg = nvgCreateContext(); 31 if (nvg is null) assert(0, "cannot initialize NanoVega"); 32 }; 33 34 // this callback will be called when we will need to repaint our window 35 sdmain.redrawOpenGlScene = delegate () { 36 // fix viewport (we can do this in resize event, or here, it doesn't matter) 37 glViewport(0, 0, sdmain.width, sdmain.height); 38 39 // clear window 40 glClearColor(0, 0, 0, 0); 41 glClear(glNVGClearFlags); // use NanoVega API to get flags for OpenGL call 42 43 { 44 nvg.beginFrame(sdmain.width, sdmain.height); // begin rendering 45 scope(exit) nvg.endFrame(); // and flush render queue on exit 46 47 nvg.beginPath(); // start new path 48 nvg.roundedRect(20.5, 30.5, sdmain.width-40, sdmain.height-60, 8); // .5 to draw at pixel center (see NanoVega documentation) 49 // now set filling mode for our rectangle 50 // you can create colors using HTML syntax, or with convenient constants 51 nvg.fillPaint = nvg.linearGradient(20.5, 30.5, sdmain.width-40, sdmain.height-60, NVGColor("#f70"), NVGColor.green); 52 // now fill our rect 53 nvg.fill(); 54 // and draw a nice outline 55 nvg.strokeColor = NVGColor.white; 56 nvg.strokeWidth = 2; 57 nvg.stroke(); 58 // that's all, folks! 59 } 60 }; 61 62 sdmain.eventLoop(0, // no pulse timer required 63 delegate (KeyEvent event) { 64 if (event == "*-Q" || event == "Escape") { sdmain.close(); return; } // quit on Q, Ctrl+Q, and so on 65 }, 66 ); 67 68 flushGui(); // let OS do it's cleanup 69 }
The NanoVega API is modeled loosely on HTML5 canvas API. If you know canvas, you're up to speed with NanoVega in no time.