arsd.nanovega

The NanoVega API is modeled loosely on HTML5 canvas API. If you know canvas, you're up to speed with NanoVega in no time.

D code with nanovega:
import arsd.nanovega;
import arsd.simpledisplay;

void main () {
	// The NVGWindow class creates a window and sets up the nvg context for you
	// you can also do these steps yourself, see the other examples in these docs
	auto window = new NVGWindow(800, 600, "NanoVega Simple Sample");

	window.redrawNVGScene = delegate (nvg) {
		nvg.beginPath(); // start new path
		nvg.roundedRect(20.5, 30.5, window.width-40, window.height-60, 8); // .5 to draw at pixel center (see NanoVega documentation)
		// now set filling mode for our rectangle
		// you can create colors using HTML syntax, or with convenient constants
		nvg.fillPaint = nvg.linearGradient(20.5, 30.5, window.width-40, window.height-60,
		NVGColor("#f70"), NVGColor.green);
		// now fill our rect
		nvg.fill();
		// and draw a nice outline
		nvg.strokeColor = NVGColor.white;
		nvg.strokeWidth = 2;
		nvg.stroke();
		// that's all, folks!
	};

	window.eventLoop(0,
		delegate (KeyEvent event) {
			if (event == "*-Q" || event == "Escape") { window.close(); return; } // quit on Q, Ctrl+Q, and so on
		},
	);
}
Javascript code with HTML5 Canvas
<!DOCTYPE html>
<html>
<head>
	<title>NanoVega Simple Sample (HTML5 Translation)</title>
	<style>
		body { background-color: black; }
	</style>
</head>
<body>
	<canvas id="my-canvas" width="800" height="600"></canvas>
<script>
	var canvas = document.getElementById("my-canvas");
	var context = canvas.getContext("2d");

	context.beginPath();

	context.rect(20.5, 30.5, canvas.width - 40, canvas.height - 60);

	var gradient = context.createLinearGradient(20.5, 30.5, canvas.width - 40, canvas.height - 60);
	gradient.addColorStop(0, "#f70");
	gradient.addColorStop(1, "green");

	context.fillStyle = gradient;
	context.fill();
	context.closePath();
	context.strokeStyle = "white";
	context.lineWidth = 2;
	context.stroke();
</script>
</body>
</html>
This library can use either inbuilt or BindBC (external dependency) provided bindings for OpenGL and FreeType. Former are used by default, latter can be activated by passing the bindbc version specifier to the compiler.

Public Imports

iv.stb.ttf
public import iv.stb.ttf;
Undocumented in source.
arsd.ttf
public import arsd.ttf;
Undocumented in source.
stb_truetype
public import stb_truetype;
Undocumented in source.
iv.freetype
public import iv.freetype;
Undocumented in source.
bindbc.freetype
public import bindbc.freetype;
Undocumented in source.
iv.freetype
public import iv.freetype;
Undocumented in source.

Members

Context management

Context Management

Functions to create and destory NanoVega context.

Context management Aliases

NVGContext
alias NVGContext = NVGcontextinternal*

Pointer to opaque NanoVega context structure.

Context management Enums

NVGContextFlag
enum NVGContextFlag

Context creation flags.

Context management Functions

devicePixelRatio
float devicePixelRatio(NVGContext ctx)

valid only inside beginFrame/endFrame

glNVGClearFlags
uint glNVGClearFlags()

Returns flags for glClear().

height
int height(NVGContext ctx)

valid only inside beginFrame/endFrame

inFrame
bool inFrame(NVGContext ctx)

Returns true if beginFrame was called, and neither endFrame, nor cancelFrame were.

kill
void kill(NVGContext ctx)

Delete NanoVega context.

nvgCreateContext
NVGContext nvgCreateContext(const(NVGContextFlag)[] flagList)

Creates NanoVega contexts for OpenGL2+.

pickid
int pickid(NVGContext ctx)

>=0: this pickid will be assigned to all filled/stroked paths

pickid
void pickid(NVGContext ctx, int v)

>=0: this pickid will be assigned to all filled/stroked paths

pickmode
uint pickmode(NVGContext ctx)

pick autoregistration mode; see NVGPickKind

pickmode
void pickmode(NVGContext ctx, uint v)

pick autoregistration mode; see NVGPickKind

tesselation
NVGTesselation tesselation(NVGContext ctx)

Get current Bezier tesselation mode. See NVGTesselation.

tesselation
void tesselation(NVGContext ctx, NVGTesselation v)

Set current Bezier tesselation mode. See NVGTesselation.

valid
bool valid(NVGContext ctx)

Returns true if the given context is not null and can be used for painting.

width
int width(NVGContext ctx)

valid only inside beginFrame/endFrame

Context management Manifest constants

NVGNoPick
enum NVGNoPick;

pickid to stop autoregistration.

Frame management

Frame Management

To start drawing with NanoVega context, you have to "begin frame", and then "end frame" to flush your rendering commands to GPU.

Frame management Functions

beginFrame
void beginFrame(NVGContext ctx, int windowWidth, int windowHeight, float devicePixelRatio)

Begin drawing a new frame.

cancelFrame
void cancelFrame(NVGContext ctx)

Cancels drawing the current frame. Cancels path recording.

endFrame
void endFrame(NVGContext ctx)
replayRecording
void replayRecording(NVGContext ctx, NVGPathSet svp, NVGColor fillTint)
void replayRecording(NVGContext ctx, NVGPathSet svp)

Ends drawing the current frame (flushing remaining render state). Commits recorded paths.

Composite operation

Composite Operation

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.

Composite operation Enums

NVGBlendFactor
enum NVGBlendFactor

Blending type.

NVGCompositeOperation
enum NVGCompositeOperation

Composite operation (HTML5-alike).

Composite operation Functions

globalCompositeBlendFunc
void globalCompositeBlendFunc(NVGContext ctx, NVGBlendFactor sfactor, NVGBlendFactor dfactor)

Sets the composite operation with custom pixel arithmetic.

globalCompositeBlendFuncSeparate
void globalCompositeBlendFuncSeparate(NVGContext ctx, NVGBlendFactor srcRGB, NVGBlendFactor dstRGB, NVGBlendFactor srcAlpha, NVGBlendFactor dstAlpha)

Sets the composite operation with custom pixel arithmetic for RGB and alpha components separately.

globalCompositeOperation
void globalCompositeOperation(NVGContext ctx, NVGCompositeOperation op)

Sets the composite operation.

Composite operation Structs

NVGCompositeOperationState
struct NVGCompositeOperationState

Composite operation state.

Color utils

Color Utils

Colors in NanoVega are stored as ARGB. Zero alpha means "transparent color".

Color utils Aliases

nvgHSL
alias nvgHSL = nvgHSLA

Returns color value specified by hue, saturation and lightness. HSL values are all in range [0..1], alpha will be set to 255.

Color utils Functions

nvgHSLA
NVGColor nvgHSLA(float h, float s, float l, ubyte a)

Returns color value specified by hue, saturation and lightness and alpha. HSL values are all in range [0..1], alpha in range [0..255].

nvgHSLA
NVGColor nvgHSLA(float h, float s, float l, float a)

Returns color value specified by hue, saturation and lightness and alpha. HSL values and alpha are all in range [0..1].

nvgLerpRGBA
NVGColor nvgLerpRGBA(NVGColor c0, NVGColor c1, float u)

Linearly interpolates from color c0 to c1, and returns resulting color value.

nvgRGB
NVGColor nvgRGB(const(char)[] srgb)

Returns a color value from string form. Supports: "#rgb", "#rrggbb", "#argb", "#aarrggbb"

nvgRGB
NVGColor nvgRGB(int r, int g, int b)

Returns a color value from red, green, blue values. Alpha will be set to 255 (1.0f).

nvgRGBA
NVGColor nvgRGBA(const(char)[] srgb)

Returns a color value from string form. Supports: "#rgb", "#rrggbb", "#argb", "#aarrggbb"

nvgRGBA
NVGColor nvgRGBA(int r, int g, int b, int a)

Returns a color value from red, green, blue and alpha values.

nvgRGBAf
NVGColor nvgRGBAf(float r, float g, float b, float a)

Returns a color value from red, green, blue and alpha values.

nvgRGBf
NVGColor nvgRGBf(float r, float g, float b)

Returns a color value from red, green, blue values. Alpha will be set to 1.0f.

nvgTransRGBA
NVGColor nvgTransRGBA(NVGColor c, ubyte a)
nvgTransRGBAf
NVGColor nvgTransRGBAf(NVGColor c, float a)

Returns new color with transparency (alpha) set to a.

Color utils Structs

NVGColor
struct NVGColor

NanoVega RGBA color

NVGHSL
struct NVGHSL

NanoVega A-HSL color

Matrices

Matrices and Transformations

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].

Matrices Functions

nvgDegToRad
float nvgDegToRad(float deg)

Converts degrees to radians.

nvgRadToDeg
float nvgRadToDeg(float rad)

Converts radians to degrees.

Matrices Structs

NVGMatrix
struct NVGMatrix

Matrix class.

State handling

State Handling

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.

State handling Functions

canRestore
bool canRestore(NVGContext ctx)

Returns true if we have any saved state.

canSave
bool canSave(NVGContext ctx)

Returns true if we have any room in state stack. It is guaranteed to have at least 32 stack slots.

renderBlocked
bool renderBlocked(NVGContext ctx)

Returns true if rendering is currently blocked.

renderBlocked
void renderBlocked(NVGContext ctx, bool v)

Blocks/unblocks rendering

reset
void reset(NVGContext ctx)

Resets current render state to default values. Does not affect the render state stack.

restore
bool restore(NVGContext ctx)

Pops and restores current render state.

save
bool save(NVGContext ctx)

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.

setRenderBlocked
bool setRenderBlocked(NVGContext ctx, bool v)

Blocks/unblocks rendering; returns previous state.

Render styles

Render Styles

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.

Render styles Enums

NVGLineCap
enum NVGLineCap

Line cap style.

Render styles Functions

evenOddFill
void evenOddFill(NVGContext ctx)

Sets filling mode to "even-odd".

fillColor
void fillColor(NVGContext ctx, NVGColor color)

Sets current fill style to a solid color.

fillColor
void fillColor(NVGContext ctx, Color color)

Sets current fill style to a solid color.

fillPaint
void fillPaint(NVGContext ctx, NVGPaint paint)

Sets current fill style to a paint, which can be a one of the gradients or a pattern.

fillPaint
void fillPaint(NVGContext ctx, NVGLGS lgs)

Sets current fill style to a multistop linear gradient.

globalAlpha
void globalAlpha(NVGContext ctx, float alpha)

Sets the transparency applied to all rendered shapes. Already transparent paths will get proportionally more transparent as well.

lineCap
void lineCap(NVGContext ctx, NVGLineCap cap)

Sets how the end of the line (cap) is drawn, Can be one of: NVGLineCap.Butt (default), NVGLineCap.Round, NVGLineCap.Square.

lineJoin
void lineJoin(NVGContext ctx, NVGLineCap join)

Sets how sharp path corners are drawn. Can be one of NVGLineCap.Miter (default), NVGLineCap.Round, NVGLineCap.Bevel.

miterLimit
void miterLimit(NVGContext ctx, float limit)

Sets the miter limit of the stroke style. Miter limit controls when a sharp corner is beveled.

nonZeroFill
void nonZeroFill(NVGContext ctx)

Sets filling mode to "non-zero" (this is default mode).

setLineDash
void setLineDash(NVGContext ctx, const(float)[] dashdata)

Sets stroke dashing, using (dash_length, gap_length) pairs. Current limit is 16 pairs. Resets dash start to zero.

setLineDashStart
void setLineDashStart(NVGContext ctx, float dashStart)

Sets stroke dashing, using (dash_length, gap_length) pairs. Current limit is 16 pairs.

shapeAntiAlias
void shapeAntiAlias(NVGContext ctx, bool enabled)

Sets whether to draw antialias for stroke and fill. It's enabled by default.

strokeColor
void strokeColor(NVGContext ctx, Color color)

Sets current stroke style to a solid color.

strokeColor
void strokeColor(NVGContext ctx, NVGColor color)

Sets current stroke style to a solid color.

strokePaint
void strokePaint(NVGContext ctx, NVGPaint paint)

Sets current stroke style to a paint, which can be a one of the gradients or a pattern.

strokeWidth
void strokeWidth(NVGContext ctx, float width)

Sets the stroke width of the stroke style.

Render styles Structs

NVGPaint
struct NVGPaint

Paint parameters for various fills. Don't change anything here!

Render transformations

Render Transformations

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.

Render transformations Functions

currTransform
NVGMatrix currTransform(NVGContext ctx)

Returns current transformation matrix.

currTransform
void currTransform(NVGContext ctx, NVGMatrix m)

Sets current transformation matrix.

resetTransform
void resetTransform(NVGContext ctx)

Resets current transform to an identity matrix.

rotate
void rotate(NVGContext ctx, float angle)

Rotates current coordinate system. Angle is specified in radians.

scale
void scale(NVGContext ctx, float x, float y)

Scales the current coordinate system.

skewX
void skewX(NVGContext ctx, float angle)

Skews the current coordinate system along X axis. Angle is specified in radians.

skewY
void skewY(NVGContext ctx, float angle)

Skews the current coordinate system along Y axis. Angle is specified in radians.

transform
void transform(NVGContext ctx, NVGMatrix mt)

Premultiplies current coordinate system by specified matrix.

translate
void translate(NVGContext ctx, float x, float y)

Translates current coordinate system.

Scissoring

Scissoring

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.

Scissoring Functions

intersectScissor
void intersectScissor(NVGContext ctx, float x, float y, float w, float h)

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.

intersectScissor
void intersectScissor(NVGContext ctx, float[] args)

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.

resetScissor
void resetScissor(NVGContext ctx)

Reset and disables scissoring.

scissor
void scissor(NVGContext ctx, float x, float y, float w, float h)

Sets the current scissor rectangle. The scissor rectangle is transformed by the current transform.

scissor
void scissor(NVGContext ctx, float[] args)

Sets the current scissor rectangle. The scissor rectangle is transformed by the current transform. Arguments: [x, y, w, h]*

Images

Images

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.

Images Enums

NVGImageFlag
enum NVGImageFlag

Image creation flags.

Images Functions

createImage
NVGImage createImage(NVGContext ctx, const(char)[] filename, const(NVGImageFlag)[] imageFlagsList)

Creates image by loading it from the disk from specified file name. Returns handle to the image or 0 on error.

createImageFromMemoryImage
NVGImage createImageFromMemoryImage(NVGContext ctx, MemoryImage img, const(NVGImageFlag)[] imageFlagsList)

Creates image by loading it from the specified memory image. Returns handle to the image or 0 on error.

createImageMem
NVGImage createImageMem(NVGContext ctx, const(ubyte)* data, int ndata, const(NVGImageFlag)[] imageFlagsList)

Creates image by loading it from the specified chunk of memory. Returns handle to the image or 0 on error.

createImageRGBA
NVGImage createImageRGBA(NVGContext ctx, int w, int h, const(void)[] data, const(NVGImageFlag)[] imageFlagsList)

Creates image from specified image data. Returns handle to the image or 0 on error.

deleteImage
void deleteImage(NVGContext ctx, NVGImage image)

Deletes created image.

glCreateImageFromHandleGL2
int glCreateImageFromHandleGL2(NVGContext ctx, GLuint textureId, int w, int h, int imageFlags)

Using OpenGL texture id creates GLNVGtexture and return its id.

glCreateImageFromOpenGLTexture
NVGImage glCreateImageFromOpenGLTexture(NVGContext ctx, GLuint textureId, int w, int h, int imageFlags)

Create NVGImage from OpenGL texture id.

glImageHandleGL2
GLuint glImageHandleGL2(NVGContext ctx, int image)

Returns OpenGL texture id for NanoVega image.

imageSize
void imageSize(NVGContext ctx, NVGImage image, int w, int h)

Returns the dimensions of a created image.

updateImage
void updateImage(NVGContext ctx, NVGImage image, const(void)[] data)

Updates image data specified by image handle.

Images Structs

NVGImage
struct NVGImage

NanoVega image handle.

Paints

Paints

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.

Paints Functions

asPaint
NVGPaint asPaint(NVGContext ctx, NVGLGS lgs)

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.

boxGradient
NVGPaint boxGradient(NVGContext ctx, float x, float y, float w, float h, float r, float f, Color icol, Color ocol)

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.

boxGradient
NVGPaint boxGradient(NVGContext ctx, float x, float y, float w, float h, float r, float f, NVGColor icol, NVGColor ocol)

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.

createLinearGradientWithStops
NVGLGS createLinearGradientWithStops(NVGContext ctx, float sx, float sy, float ex, float ey, const(NVGGradientStop)[] stops)

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);.

THIS IS EXPERIMENTAL API AND MAY BE CHANGED/BROKEN IN NEXT RELEASES!
imagePattern
NVGPaint imagePattern(NVGContext ctx, float cx, float cy, float w, float h, float angle, NVGImage image, float alpha)

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.

linearGradient
NVGPaint linearGradient(NVGContext ctx, float sx, float sy, float ex, float ey, Color icol, Color ocol)

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.

linearGradient
NVGPaint linearGradient(NVGContext ctx, float sx, float sy, float ex, float ey, Color icol, float midp, Color mcol, Color ocol)

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.

linearGradient
NVGPaint linearGradient(NVGContext ctx, float sx, float sy, float ex, float ey, NVGColor icol, NVGColor ocol)

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.

linearGradient
NVGPaint linearGradient(NVGContext ctx, float sx, float sy, float ex, float ey, NVGColor icol, float midp, NVGColor mcol, NVGColor ocol)

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.

radialGradient
NVGPaint radialGradient(NVGContext ctx, float cx, float cy, float inr, float outr, Color icol, Color ocol)

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.

radialGradient
NVGPaint radialGradient(NVGContext ctx, float cx, float cy, float inr, float outr, NVGColor icol, NVGColor ocol)

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.

Paints Structs

NVGGradientStop
struct NVGGradientStop

Gradient Stop Point.

THIS IS EXPERIMENTAL API AND MAY BE CHANGED/BROKEN IN NEXT RELEASES!
NVGLGS
struct NVGLGS

Linear gradient with multiple stops.

THIS IS EXPERIMENTAL API AND MAY BE CHANGED/BROKEN IN NEXT RELEASES!

Gpu affine

Render-Time Affine Transformations

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.

Don't use this for scaling or skewing, or your image will be heavily distorted!

Gpu affine Functions

affineGPU
void affineGPU(NVGContext ctx, NVGMatrix mat)

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.

affineGPU
NVGMatrix affineGPU(NVGContext ctx)

Get current GPU affine transformatin matrix.

gpuUntransformPoint
void gpuUntransformPoint(NVGContext ctx, float* dx, float* dy, float x, float y)

"Untransform" point using current GPU affine matrix.

Paths

Paths

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.

Paths Enums

NVGSolidity
enum NVGSolidity

Path solidity.

NVGWinding
enum NVGWinding

Path winding.

Paths Functions

arc
void arc(NVGContext ctx, NVGWinding dir, float cx, float cy, float r, float a0, float a1)

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.

arc
void arc(NVGContext ctx, NVGWinding dir, float[] args)

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.

arcTo
void arcTo(NVGContext ctx, float x1, float y1, float x2, float y2, float radius)

Adds an arc segment at the corner defined by the last path point, and two specified points.

arcTo
void arcTo(NVGContext ctx, float[] args)

Adds an arc segment at the corner defined by the last path point, and two specified points. Arguments: [x1, y1, x2, y2, radius]*

beginPath
void beginPath(NVGContext ctx)

Clears the current path and sub-paths.

bezierTo
void bezierTo(NVGContext ctx, float c1x, float c1y, float c2x, float c2y, float x, float y)

Adds cubic bezier segment from last point in the path via two control points to the specified point.

bezierTo
void bezierTo(NVGContext ctx, float[] args)

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]*

circle
void circle(NVGContext ctx, float cx, float cy, float r)

Creates new circle shaped sub-path.

circle
void circle(NVGContext ctx, float[] args)

Creates new circle shaped sub-path. Arguments: [cx, cy, r]*

closePath
void closePath(NVGContext ctx)

Closes current sub-path with a line segment.

ellipse
void ellipse(NVGContext ctx, float cx, float cy, float rx, float ry)

Creates new ellipse shaped sub-path.

ellipse
void ellipse(NVGContext ctx, float[] args)

Creates new ellipse shaped sub-path. Arguments: [cx, cy, rx, ry]*

fill
void fill(NVGContext ctx)

Fills the current path with current fill style.

getCurrPathOutline
NVGPathOutline getCurrPathOutline(NVGContext ctx)

Return outline of the current path. Returned outline is not flattened.

lineTo
void lineTo(NVGContext ctx, float x, float y)

Adds line segment from the last point in the path to the specified point.

lineTo
void lineTo(NVGContext ctx, float[] args)

Adds line segment from the last point in the path to the specified point. Arguments: [x, y]*

moveTo
void moveTo(NVGContext ctx, float x, float y)

Starts new sub-path with specified point as first point.

moveTo
void moveTo(NVGContext ctx, float[] args)

Starts new sub-path with specified point as first point. Arguments: [x, y]*

pathWinding
void pathWinding(NVGContext ctx, NVGWinding dir)
void pathWinding(NVGContext ctx, NVGSolidity dir)

Sets the current sub-path winding, see NVGWinding and NVGSolidity.

quadTo
void quadTo(NVGContext ctx, float cx, float cy, float x, float y)

Adds quadratic bezier segment from last point in the path via a control point to the specified point.

quadTo
void quadTo(NVGContext ctx, float[] args)

Adds quadratic bezier segment from last point in the path via a control point to the specified point. Arguments: [cx, cy, x, y]*

rect
void rect(NVGContext ctx, float[] args)

Creates new rectangle shaped sub-path. Arguments: [x, y, w, h]*

rect
void rect(NVGContext ctx, float x, float y, float w, float h)

Creates new rectangle shaped sub-path.

roundedRect
void roundedRect(NVGContext ctx, float[] args)

Creates new rounded rectangle shaped sub-path. Arguments: [x, y, w, h, radius]*

roundedRect
void roundedRect(NVGContext ctx, float x, float y, float w, float h, float radius)

Creates new rounded rectangle shaped sub-path.

roundedRectEllipse
void roundedRectEllipse(NVGContext ctx, float x, float y, float w, float h, float rw, float rh)

Creates new rounded rectangle shaped sub-path. Specify ellipse width and height to round corners according to it.

roundedRectEllipse
void roundedRectEllipse(NVGContext ctx, float[] args)

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]*

roundedRectVarying
void roundedRectVarying(NVGContext ctx, float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft)

Creates new rounded rectangle shaped sub-path. This one allows you to specify different rounding radii for each corner.

roundedRectVarying
void roundedRectVarying(NVGContext ctx, float[] args)

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]*

stroke
void stroke(NVGContext ctx)

Fills the current path with current stroke style.

Picking api

Picking API

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.

Picking API completely ignores clipping. If you want to check for clip regions, you have to manually register them as fill/stroke paths, and perform the necessary logic. See hitTestForId function.

Picking api Enums

NVGPickKind
enum NVGPickKind

Pick type query. Used in hitTest and hitTestAll.

Picking api Functions

currFillHitId
void currFillHitId(NVGContext ctx, int id)

Marks the fill of the current path as pickable with the specified id. Note that you can create and mark path without rasterizing it.

currStrokeHitId
void currStrokeHitId(NVGContext ctx, int id)

Marks the stroke of the current path as pickable with the specified id. Note that you can create and mark path without rasterizing it.

hitTest
int hitTest(NVGContext ctx, float x, float y, NVGPickKind kind)

Returns the id of the pickable shape containing x,y or NVGNoPick if no shape was found.

hitTestAll
int[] hitTestAll(NVGContext ctx, float x, float y, NVGPickKind kind, int[] ids)

Fills ids with a list of the top most hit ids (from bottom to top) under the specified position. Returns the slice of ids.

hitTestCurrFill
bool hitTestCurrFill(NVGContext ctx, float x, float y)

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.

hitTestCurrStroke
bool hitTestCurrStroke(NVGContext ctx, float x, float y)

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.

hitTestDG
int hitTestDG(NVGContext ctx, float x, float y, NVGPickKind kind, DG dg)

Call delegate dg for each path under the specified position (in no particular order). Returns the id of the path for which delegate dg returned true or NVGNoPick. dg is: bool delegate (int id, int order) -- order is path ordering (ascending).

hitTestForId
bool hitTestForId(NVGContext ctx, int id, float x, float y, NVGPickKind kind)

Returns true if the path with the given id contains x,y.

Clipping

Clipping with paths

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.

Clipping Aliases

clipFill
alias clipFill = clip

Sets current path as clipping region.

Clipping Enums

NVGClipMode
enum NVGClipMode

Mask combining more

Clipping Functions

clip
void clip(NVGContext ctx, NVGClipMode aclipmode)

Sets current path as clipping region.

clipStroke
void clipStroke(NVGContext ctx, NVGClipMode aclipmode)

Sets current path' stroke as clipping region.

Text api

Text

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.

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.

Text api Functions

addFontsFrom
void addFontsFrom(NVGContext ctx, NVGContext source)

Add fonts from another context. This is more effective than reloading fonts, 'cause font data will be shared.

charOutline
NVGPathOutline charOutline(NVGContext ctx, dchar dch)

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.

charPathBounds
bool charPathBounds(NVGContext ctx, dchar dch, float[] bounds)

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.

charToPath
bool charToPath(NVGContext ctx, dchar dch, float[] bounds)

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.

createFont
int createFont(NVGContext ctx, const(char)[] name, const(char)[] path)

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).

createFontMem
int createFontMem(NVGContext ctx, const(char)[] name, ubyte* data, int ndata, bool freeData)

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.

findFont
int findFont(NVGContext ctx, const(char)[] name)

Finds a loaded font of specified name, and returns handle to it, or FONS_INVALID (aka -1) if the font is not found.

fontBlur
float fontBlur(NVGContext ctx)

Gets the blur of current text style.

fontBlur
void fontBlur(NVGContext ctx, float blur)

Sets the blur of current text style.

fontFace
void fontFace(NVGContext ctx, const(char)[] font)

Sets the font face based on specified name of current text style.

fontFaceId
void fontFaceId(NVGContext ctx, int font)

Sets the font face based on specified id of current text style.

fontFaceId
int fontFaceId(NVGContext ctx)

Gets the font face based on specified id of current text style.

fontSize
void fontSize(NVGContext ctx, float size)

Sets the font size of current text style.

fontSize
float fontSize(NVGContext ctx)

Gets the font size of current text style.

kill
void kill(NVGPathOutline ol)

Destroy glyph outiline and free allocated memory.

text
float text(NVGContext ctx, float x, float y, const(T)[] str)

Draws text string at specified location. Returns next x position.

textAlign
void textAlign(NVGContext ctx, NVGTextAlign talign)
void textAlign(NVGContext ctx, NVGTextAlign.H h)
void textAlign(NVGContext ctx, NVGTextAlign.V v)
void textAlign(NVGContext ctx, NVGTextAlign.H h, NVGTextAlign.V v)
void textAlign(NVGContext ctx, NVGTextAlign.V v, NVGTextAlign.H h)

Sets the text align of current text style, see NVGTextAlign for options.

textAlign
NVGTextAlign textAlign(NVGContext ctx)

Gets the text align of current text style, see NVGTextAlign for options.

textBounds
float textBounds(NVGContext ctx, float x, float y, const(T)[] str, float[] bounds)

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.

textBox
void textBox(NVGContext ctx, float x, float y, float breakRowWidth, const(T)[] str)

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).

textBoxBounds
void textBoxBounds(NVGContext ctx, float x, float y, float breakRowWidth, const(T)[] str, float[] bounds)

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.

textBreakLines
int textBreakLines(NVGContext ctx, const(T)[] str, float breakRowWidth, DG dg)

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.

textBreakLines
NVGTextRow!T[] textBreakLines(NVGContext ctx, const(T)[] str, float breakRowWidth, NVGTextRow!T[] 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).

textExtents
void textExtents(NVGContext ctx, const(T)[] str, float* w, float* h)

Measures the specified text string. Returns horizontal and vertical sizes of the measured text. Measured values are returned in local coordinate space.

textFontAscender
float textFontAscender(NVGContext ctx)

Returns font ascender (positive), measured in local coordinate space.

textFontDescender
float textFontDescender(NVGContext ctx)

Returns font descender (negative), measured in local coordinate space.

textFontHeight
float textFontHeight(NVGContext ctx)

Returns font line height (without line spacing), measured in local coordinate space.

textGlyphPositions
NVGGlyphPosition[] textGlyphPositions(NVGContext ctx, float x, float y, const(T)[] str, NVGGlyphPosition[] positions)
int textGlyphPositions(NVGContext ctx, float x, float y, const(T)[] str, DG dg)

Calculates the glyph x positions of the specified text. Measured values are returned in local coordinate space.

textLetterSpacing
void textLetterSpacing(NVGContext ctx, float spacing)

Sets the letter spacing of current text style.

textLetterSpacing
float textLetterSpacing(NVGContext ctx)

Gets the letter spacing of current text style.

textLineHeight
void textLineHeight(NVGContext ctx, float lineHeight)

Sets the proportional line height of current text style. The line height is specified as multiple of font size.

textLineHeight
float textLineHeight(NVGContext ctx)

Gets the proportional line height of current text style. The line height is specified as multiple of font size.

textMetrics
void textMetrics(NVGContext ctx, float* ascender, float* descender, float* lineh)

Returns the vertical metrics based on the current text style. Measured values are returned in local coordinate space.

textWidth
float textWidth(NVGContext ctx, const(T)[] str)

Measures the specified text string. Returns horizontal size of the measured text. Measured values are returned in local coordinate space.

Text api Structs

NVGGlyphPosition
struct NVGGlyphPosition

Glyph position info.

NVGPathOutline
struct NVGPathOutline

charOutline will return NVGPathOutline.

NVGTextAlign
struct NVGTextAlign

Text align.

NVGTextRow
struct NVGTextRow(CT)

Text row storage.

TextBoundsIterator
struct TextBoundsIterator

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.

Font stash

Low-Level Font Engine (FontStash)

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.

Font stash Aliases

FONSContext
alias FONSContext = FONScontextInternal*

FontStash context

Font stash Functions

fonsContext
FONSContext fonsContext(NVGContext ctx)

Returns FontStash context of the given NanoVega context.

fonsScale
float fonsScale(NVGContext ctx)

Returns scale that should be applied to FontStash parameters due to matrix transformations on the context (or 1)

kill
void kill(FONSContext stash)

Free all resources used by the stash, and stash itself.

setupCtxFrom
bool setupCtxFrom(NVGContext ctx, FONSContext stash)

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.

setupFonsFrom
bool setupFonsFrom(FONSContext stash, NVGContext ctx)

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.

Font stash Manifest constants

FONS_INVALID
enum FONS_INVALID;

Invald font id.

Font stash Structs

FONSParams
struct FONSParams

Initial parameters for new FontStash.

FONSTextBoundsIterator
struct FONSTextBoundsIterator

This iterator can be used to do text measurement.

Don't add new fonts to stash while you are iterating, or you WILL get segfault!
FONScontextInternal
struct FONScontextInternal

FontStash context (internal definition). Don't use it derectly, it was made public only to generate documentation.

Other

Other Classes

NVGWindow
class NVGWindow

A SimpleWindow subclass that encapsulates some nanovega defaults. You just set a redrawNVGScene delegate and, optionally, your nromal event handlers for simpledisplay, and the rest is set up for you.

Other Enums

NVGTesselation
enum NVGTesselation

Bezier curve rasterizer.

Other Functions

nvgClampToByte
ubyte nvgClampToByte(T n)

this is branchless for ints on x86, and even for longs on x86_64

renderPathComplex
bool renderPathComplex(NVGContext ctx, int pathidx)

Returns "complex path" flag for the given render path.

renderPathCount
int renderPathCount(NVGContext ctx)

Returns number of tesselated pathes in context.

renderPathFillVertices
const(NVGVertex)[] renderPathFillVertices(NVGContext ctx, int pathidx)

Get vertices of "fill" triangle fan for the given render path. Can return empty slice.

renderPathStrokeVertices
const(NVGVertex)[] renderPathStrokeVertices(NVGContext ctx, int pathidx)

Get vertices of "stroke" triangle strip for the given render path. Can return empty slice.

renderPathWinding
NVGWinding renderPathWinding(NVGContext ctx, int pathidx)

Returns winding for the given render path.

Other Imports

isDelegate (from std.traits)
public import std.traits : isFunctionPointer, isDelegate;
Undocumented in source.
isFunctionPointer (from std.traits)
public import std.traits : isFunctionPointer, isDelegate;
Undocumented in source.
nvg__absf (from core.math)
public import core.math : nvg__absf = fabs;
Undocumented in source.
nvg__acosf (from core.stdc.math)
public import core.stdc.math : nvg__sqrtf = sqrtf, nvg__modf = fmodf, nvg__sinf = sinf, nvg__cosf = cosf, nvg__tanf = tanf, nvg__atan2f = atan2f, nvg__acosf = acosf, nvg__ceilf = ceilf;
Undocumented in source.
nvg__atan2f (from core.stdc.math)
public import core.stdc.math : nvg__sqrtf = sqrtf, nvg__modf = fmodf, nvg__sinf = sinf, nvg__cosf = cosf, nvg__tanf = tanf, nvg__atan2f = atan2f, nvg__acosf = acosf, nvg__ceilf = ceilf;
Undocumented in source.
nvg__ceilf (from core.stdc.math)
public import core.stdc.math : nvg__sqrtf = sqrtf, nvg__modf = fmodf, nvg__sinf = sinf, nvg__cosf = cosf, nvg__tanf = tanf, nvg__atan2f = atan2f, nvg__acosf = acosf, nvg__ceilf = ceilf;
Undocumented in source.
nvg__cosf (from core.stdc.math)
public import core.stdc.math : nvg__sqrtf = sqrtf, nvg__modf = fmodf, nvg__sinf = sinf, nvg__cosf = cosf, nvg__tanf = tanf, nvg__atan2f = atan2f, nvg__acosf = acosf, nvg__ceilf = ceilf;
Undocumented in source.
nvg__lrintf (from core.stdc.math)
public import core.stdc.math : nvg__lrintf = lrintf;
Undocumented in source.
nvg__modf (from core.stdc.math)
public import core.stdc.math : nvg__sqrtf = sqrtf, nvg__modf = fmodf, nvg__sinf = sinf, nvg__cosf = cosf, nvg__tanf = tanf, nvg__atan2f = atan2f, nvg__acosf = acosf, nvg__ceilf = ceilf;
Undocumented in source.
nvg__sinf (from core.stdc.math)
public import core.stdc.math : nvg__sqrtf = sqrtf, nvg__modf = fmodf, nvg__sinf = sinf, nvg__cosf = cosf, nvg__tanf = tanf, nvg__atan2f = atan2f, nvg__acosf = acosf, nvg__ceilf = ceilf;
Undocumented in source.
nvg__sqrtf (from core.stdc.math)
public import core.stdc.math : nvg__sqrtf = sqrtf, nvg__modf = fmodf, nvg__sinf = sinf, nvg__cosf = cosf, nvg__tanf = tanf, nvg__atan2f = atan2f, nvg__acosf = acosf, nvg__ceilf = ceilf;
Undocumented in source.
nvg__tanf (from core.stdc.math)
public import core.stdc.math : nvg__sqrtf = sqrtf, nvg__modf = fmodf, nvg__sinf = sinf, nvg__cosf = cosf, nvg__tanf = tanf, nvg__atan2f = atan2f, nvg__acosf = acosf, nvg__ceilf = ceilf;
Undocumented in source.

Other Manifest constants

NVG_KAPPA90
enum NVG_KAPPA90;

Length proportional to radius of a cubic bezier handle for 90deg arcs.

NanoVegaHasCharOutline
enum NanoVegaHasCharOutline;
NanoVegaHasCharOutline
enum NanoVegaHasCharOutline;
NanoVegaHasCharPathBounds
enum NanoVegaHasCharPathBounds;
NanoVegaHasCharPathBounds
enum NanoVegaHasCharPathBounds;
NanoVegaHasCharToPath
enum NanoVegaHasCharToPath;
NanoVegaHasCharToPath
enum NanoVegaHasCharToPath;
scriptable
enum scriptable;

Annotation to indicate the marked function is compatible with arsd.script.

Other Static variables

NVG_DEFAULT_TESSELATOR
NVGTesselation NVG_DEFAULT_TESSELATOR;

Default tesselator for Bezier curves.

Other Structs

NVGVertex
struct NVGVertex

General NanoVega vertex struct. Contains geometry coordinates, and (sometimes unused) texture coordinates.

Detailed Description

Creating drawing context

The drawing context is created using platform specific constructor function.

NVGContext vg = nvgCreateContext();
You must use created context ONLY in that thread where you created it. There is no way to "transfer" context between threads. Trying to do so will lead to UB.
Never issue any commands outside of beginFrame/endFrame. Trying to do so will lead to UB.

Drawing shapes with NanoVega

Drawing a simple shape using NanoVega consists of four steps:

  • begin a new shape,
  • define the path to draw,
  • set fill or stroke,
  • and finally fill or stroke the path.
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.

Understanding Composite Paths

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();

Rendering is wrong, what to do?

  • make sure you have created NanoVega context using nvgCreateContext call
  • make sure you have initialised OpenGL with stencil buffer
  • make sure you have cleared stencil buffer
  • make sure all rendering calls happen between beginFrame and endFrame
  • to enable more checks for OpenGL errors, add NVGContextFlag.Debug flag to nvgCreateContext

OpenGL state touched by the backend

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);

Examples

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     nvg = nvgCreateContext();
30     if (nvg is null) assert(0, "cannot initialize NanoVega");
31   };
32 
33   // this callback will be called when we will need to repaint our window
34   sdmain.redrawOpenGlScene = delegate () {
35     // fix viewport (we can do this in resize event, or here, it doesn't matter)
36     glViewport(0, 0, sdmain.width, sdmain.height);
37 
38     // clear window
39     glClearColor(0, 0, 0, 0);
40     glClear(glNVGClearFlags); // use NanoVega API to get flags for OpenGL call
41 
42     {
43       nvg.beginFrame(sdmain.width, sdmain.height); // begin rendering
44       scope(exit) nvg.endFrame(); // and flush render queue on exit
45 
46       nvg.beginPath(); // start new path
47       nvg.roundedRect(20.5, 30.5, sdmain.width-40, sdmain.height-60, 8); // .5 to draw at pixel center (see NanoVega documentation)
48       // now set filling mode for our rectangle
49       // you can create colors using HTML syntax, or with convenient constants
50       nvg.fillPaint = nvg.linearGradient(20.5, 30.5, sdmain.width-40, sdmain.height-60, NVGColor("#f70"), NVGColor.green);
51       // now fill our rect
52       nvg.fill();
53       // and draw a nice outline
54       nvg.strokeColor = NVGColor.white;
55       nvg.strokeWidth = 2;
56       nvg.stroke();
57       // that's all, folks!
58     }
59   };
60 
61   sdmain.eventLoop(0, // no pulse timer required
62     delegate (KeyEvent event) {
63       if (event == "*-Q" || event == "Escape") { sdmain.close(); return; } // quit on Q, Ctrl+Q, and so on
64     },
65   );
66 
67   flushGui(); // let OS do it's cleanup
68 }

Meta