svg

package
v1.2.17 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 2, 2022 License: BSD-3-Clause Imports: 38 Imported by: 9

Documentation

Overview

Package svg provides SVG rendering classes, I/O parsing: full SVG rendering

SVG currently supports most of SVG, but not:

  • Flow
  • Filter Effects
  • 3D Perspective transforms

See gi/examples/svg for a basic SVG viewer app, using the svg.Editor, which will ultimately be expanded to support more advanced editing. Also in that directory are a number of test files that stress different aspects of rendering.

svg.NodeBase is the base type for all SVG elements -- unlike Widget nodes, SVG nodes do not use layout logic, and just draw directly into a parent SVG viewport, with cumulative transforms determining drawing position, etc. The BBox values are only valid after rendering for these nodes.

It uses srwiley/rasterx for SVG-compatible rasterization, and the gi.Paint interface for drawing.

The Path element uses a compiled bytecode version of the Data path for increased speed.

Index

Constants

View Source
const SVGRefCountKey = "SVGRefCount"

Variables

View Source
var EditorProps = ki.Props{
	"EnumType:Flag": gi.KiT_VpFlags,
}
View Source
var IconAutoOpen = true

IconAutoOpen controls auto-loading of icons -- can turn this off for debugging etc

View Source
var IconProps = ki.Props{
	"EnumType:Flag":    gi.KiT_VpFlags,
	"background-color": color.Transparent,
}
View Source
var ImageProps = ki.Props{
	"EnumType:Flag": gi.KiT_NodeFlags,
	"ToolBar": ki.PropSlice{
		{"OpenImage", ki.Props{
			"desc": "Open image file for this image node, rescaling to given size -- use 0, 0 to use native image size.",
			"icon": "file-open",
			"Args": ki.PropSlice{
				{"File Name", ki.Props{
					"default-field": "Filename",
					"ext":           ".png,.jpg,.jpeg",
				}},
				{"Width", ki.Props{}},
				{"Height", ki.Props{}},
			},
		}},
		{"SaveImage", ki.Props{
			"desc": "Save image to a file.",
			"icon": "file-save",
			"Args": ki.PropSlice{
				{"File Name", ki.Props{
					"default-field": "Filename",
					"ext":           ".png,.jpg,.jpeg",
				}},
			},
		}},
	},
}

ImageProps define the ToolBar for images

View Source
var InkscapeProps = map[string]bool{
	"isstock": true,
	"stockid": true,
}

InkscapeProps are property keys that should be prefixed with "inkscape:"

View Source
var KiT_Circle = kit.Types.AddType(&Circle{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_ClipPath = kit.Types.AddType(&ClipPath{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_Editor = kit.Types.AddType(&Editor{}, EditorProps)
View Source
var KiT_Ellipse = kit.Types.AddType(&Ellipse{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_Filter = kit.Types.AddType(&Filter{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_Flow = kit.Types.AddType(&Flow{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_Group = kit.Types.AddType(&Group{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_Icon = kit.Types.AddType(&Icon{}, IconProps)
View Source
var KiT_Image = kit.Types.AddType(&Image{}, ImageProps)
View Source
var KiT_Line = kit.Types.AddType(&Line{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_Marker = kit.Types.AddType(&Marker{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_MarkerUnits = kit.Enums.AddEnumAltLower(MarkerUnitsN, kit.NotBitFlag, gist.StylePropProps, "")
View Source
var KiT_NodeBase = kit.Types.AddType(&NodeBase{}, NodeBaseProps)
View Source
var KiT_Path = kit.Types.AddType(&Path{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_PathCmds = kit.Enums.AddEnumAltLower(PcErr, kit.NotBitFlag, nil, "Pc")
View Source
var KiT_Polygon = kit.Types.AddType(&Polygon{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_Polyline = kit.Types.AddType(&Polyline{}, nil)
View Source
var KiT_Rect = kit.Types.AddType(&Rect{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_SVG = kit.Types.AddType(&SVG{}, SVGProps)
View Source
var KiT_SVGFlags = kit.Enums.AddEnumExt(gi.KiT_VpFlags, SVGFlagsN, kit.BitFlag, nil)
View Source
var KiT_Text = kit.Types.AddType(&Text{}, ki.Props{"EnumType:Flag": gi.KiT_NodeFlags})
View Source
var KiT_ViewBoxMeetOrSlice = kit.Enums.AddEnumAltLower(ViewBoxMeetOrSliceN, kit.NotBitFlag, gist.StylePropProps, "")
View Source
var NodeBaseProps = ki.Props{
	"base-type":     true,
	"EnumType:Flag": gi.KiT_NodeFlags,
}
View Source
var PathCmdNMap = map[PathCmds]int{
	PcM: 2,
	Pcm: 2,
	PcL: 2,
	Pcl: 2,
	PcH: 1,
	Pch: 1,
	PcV: 1,
	Pcv: 1,
	PcC: 6,
	Pcc: 6,
	PcS: 4,
	Pcs: 4,
	PcQ: 4,
	Pcq: 4,
	PcT: 2,
	Pct: 2,
	PcA: 7,
	Pca: 7,
	PcZ: 0,
	Pcz: 0,
}

PathCmdNMap gives the number of points per each command

View Source
var PathCmdToRune = map[PathCmds]rune{}

PathCmdToRune maps command to rune

View Source
var PathRuneToCmd = map[rune]PathCmds{
	'M': PcM,
	'm': Pcm,
	'L': PcL,
	'l': Pcl,
	'H': PcH,
	'h': Pch,
	'V': PcV,
	'v': Pcv,
	'C': PcC,
	'c': Pcc,
	'S': PcS,
	's': Pcs,
	'Q': PcQ,
	'q': Pcq,
	'T': PcT,
	't': Pct,
	'A': PcA,
	'a': Pca,
	'Z': PcZ,
	'z': Pcz,
}

PathRuneToCmd maps rune to path command

View Source
var SVGProps = ki.Props{
	"EnumType:Flag": KiT_SVGFlags,
	"ToolBar": ki.PropSlice{
		{"OpenXML", ki.Props{
			"label": "Open...",
			"desc":  "Open SVG XML-formatted file",
			"icon":  "file-open",
			"Args": ki.PropSlice{
				{"File Name", ki.Props{
					"ext": ".svg",
				}},
			},
		}},
		{"SaveXML", ki.Props{
			"label": "SaveAs...",
			"desc":  "Save SVG content to an XML-formatted file.",
			"icon":  "file-save",
			"Args": ki.PropSlice{
				{"File Name", ki.Props{
					"ext": ".svg",
				}},
			},
		}},
	},
}

Functions

func AddNewNodeGradient added in v1.2.3

func AddNewNodeGradient(gii gi.Node2D, radial bool, stops string) (*gi.Gradient, string)

AddNewNodeGradient adds a new gradient specific to given node that points to given stops name. returns the new gradient and the url that points to it (nil if parent svg cannot be found). Initializes gradient to use bounding box of object, but using userSpaceOnUse setting

func ApplyCSSSVG

func ApplyCSSSVG(node gi.Node2D, key string, css ki.Props) bool

ApplyCSSSVG applies css styles to given node, using key to select sub-props from overall properties list

func Asset added in v0.9.9

func Asset(name string) ([]byte, error)

Asset loads and returns the asset for the given name. It returns an error if the asset could not be found or could not be loaded.

func AssetDir added in v0.9.9

func AssetDir(name string) ([]string, error)

AssetDir returns the file names below a certain directory embedded in the file by go-bindata. For example if you run go-bindata on data/... and data contains the following hierarchy:

data/
  foo.txt
  img/
    a.png
    b.png

then AssetDir("data") would return []string{"foo.txt", "img"} AssetDir("data/img") would return []string{"a.png", "b.png"} AssetDir("foo.txt") and AssetDir("notexist") would return an error AssetDir("") will return []string{"data"}.

func AssetInfo added in v0.9.9

func AssetInfo(name string) (os.FileInfo, error)

AssetInfo loads and returns the asset info for the given name. It returns an error if the asset could not be found or could not be loaded.

func AssetNames added in v0.9.9

func AssetNames() []string

AssetNames returns the names of the assets. nolint: deadcode

func BBoxFromChildren added in v1.2.0

func BBoxFromChildren(gii gi.Node2D) image.Rectangle

BBoxFromChildren sets the Group BBox from children

func CloneNodeGradientProp added in v1.2.3

func CloneNodeGradientProp(gii gi.Node2D, prop string) *gi.Gradient

CloneNodeGradientProp creates a new clone of the existing gradient for node if set for given property key ("fill" or "stroke"). returns new gradient.

func DeleteNodeGradient added in v1.2.3

func DeleteNodeGradient(gii gi.Node2D, grnm string) bool

DeleteNodeGradient deletes the node-specific gradient on given node of given name, which can be a full url(# name or just the bare name. Returns true if deleted.

func DeleteNodeGradientProp added in v1.2.3

func DeleteNodeGradientProp(gii gi.Node2D, prop string) bool

DeleteNodeGradientProp deletes any existing gradient for node if set for given property key ("fill" or "stroke"). Returns true if deleted.

func EscapeText added in v1.2.0

func EscapeText(w io.Writer, s []byte, escapeNewline bool) error

XMLEscapeText writes to w the properly escaped XML equivalent of the plain text data s. If escapeNewline is true, newline XMLcharacters will be escaped.

func FirstNonGroupNode added in v1.2.3

func FirstNonGroupNode(kn ki.Ki) ki.Ki

FirstNonGroupNode returns the first item that is not a group recursing into groups until a non-group item is found.

func GradientByName added in v1.2.0

func GradientByName(gii gi.Node2D, grnm string) *gi.Gradient

GradientByName returns the gradient of given name, stored on SVG node

func GradientReadPts added in v1.2.0

func GradientReadPts(gr *gist.ColorSpec, dat []float32)

GradientReadPoints reads the UserSpaceOnUse gradient points from a slice of floating point numbers, reading from the end.

func GradientWritePts added in v1.2.0

func GradientWritePts(gr *gist.ColorSpec, dat *[]float32)

GradientWritePoints writes the UserSpaceOnUse gradient points to a slice of floating point numbers, appending to end of slice.

func IncRefCount added in v1.2.3

func IncRefCount(k ki.Ki)

func IsDefs added in v1.2.17

func IsDefs(g *gi.Node2DBase) bool

IsDefs returns true if is in the Defs of parent SVG viewport

func MustAsset added in v0.9.9

func MustAsset(name string) []byte

MustAsset is like Asset but panics when Asset would return an error. It simplifies safe initialization of global variables. nolint: deadcode

func NameFromURL added in v1.2.3

func NameFromURL(url string) string

NameFromURL returns just the name referred to in a url(#name) if it is not a url(#) format then returns empty string.

func NameId added in v1.2.0

func NameId(nm string, id int) string

NameId returns the name with given unique id. returns plain name if id == 0

func NameToURL added in v1.2.3

func NameToURL(nm string) string

NameToURL returns url as: url(#name)

func NodeFindURL added in v1.2.0

func NodeFindURL(gii gi.Node2D, url string) gi.Node2D

NodeFindURL finds a url element in the parent SVG of given node. Returns nil if not found. Works with full 'url(#Name)' string or plain name or "none"

func NodePropURL added in v1.2.0

func NodePropURL(kn ki.Ki, prop string) string

NodePropURL returns a url(#name) url from given prop name on node, or empty string if none. Returned value is just the 'name' part of the url, not the full string.

func PathCmdIsRel added in v1.2.3

func PathCmdIsRel(pc PathCmds) bool

PathCmdIsRel returns true if the path command is relative, false for absolute

func PathDataBBox added in v1.2.5

func PathDataBBox(data []PathData) mat32.Box2

PathDataBBox traverses the path data and extracts the local bounding box

func PathDataEnd

func PathDataEnd(data []PathData) (vec mat32.Vec2, ang float32)

PathDataEnd gets the ending coords and angle from the path

func PathDataIterFunc

func PathDataIterFunc(data []PathData, fun func(idx int, cmd PathCmds, ptIdx int, cp mat32.Vec2, ctrls []mat32.Vec2) bool)

PathDataIterFunc traverses the path data and calls given function on each coordinate point, passing overall starting index of coords in data stream, command, index of the points within that command, and coord values (absolute, not relative, regardless of the command type), including special control points for path commands that have them (else nil). If function returns false (use ki.Break vs. ki.Continue) then traversal is aborted. For Control points, order is in same order as in standard path stream when multiple, e.g., C,S. For A: order is: nc, prv, rad, mat32.Vec2{X: ang}, mat32.Vec2{laf, sf}}

func PathDataNext

func PathDataNext(data []PathData, i *int) float32

PathDataNext gets the next path data point, incrementing the index

func PathDataNextRel added in v1.2.3

func PathDataNextRel(data []PathData, i *int, cp mat32.Vec2) mat32.Vec2

PathDataNextRel gets the next 2 path data points as a relative vector and returns that relative vector added to current point

func PathDataNextVec added in v1.2.0

func PathDataNextVec(data []PathData, i *int) mat32.Vec2

PathDataNextVec gets the next 2 path data points as a vector

func PathDataRender

func PathDataRender(data []PathData, pc *girl.Paint, rs *girl.State)

PathDataRender traverses the path data and renders it using paint and render state -- we assume all the data has been validated and that n's are sufficient, etc

func PathDataStart

func PathDataStart(data []PathData) (vec mat32.Vec2, ang float32)

PathDataStart gets the starting coords and angle from the path

func PathDataString added in v1.2.0

func PathDataString(data []PathData) string

PathDataString returns the string representation of the path data

func PathDataValidate

func PathDataValidate(pc *girl.Paint, data *[]PathData, errstr string) error

PathDataValidate validates the path data and emits error messages on log

func PathDataXFormAbs added in v1.2.0

func PathDataXFormAbs(data []PathData, i *int, xf mat32.Mat2, lpt mat32.Vec2) mat32.Vec2

PathDataXFormAbs does the transform of next two data points as absolute coords

func PathDataXFormRel added in v1.2.0

func PathDataXFormRel(data []PathData, i *int, xf mat32.Mat2, cp mat32.Vec2) mat32.Vec2

PathDataXFormRel does the transform of next two data points as relative coords compared to given cp coordinate. returns new *absolute* coordinate

func RestoreAsset added in v0.9.9

func RestoreAsset(dir, name string) error

RestoreAsset restores an asset under the given directory

func RestoreAssets added in v0.9.9

func RestoreAssets(dir, name string) error

RestoreAssets restores an asset under the given directory recursively

func SVGNodeMarshalXML added in v1.2.0

func SVGNodeMarshalXML(itm ki.Ki, enc *XMLEncoder, setName string) string

SVGNodeMarshalXML encodes just the given node under SVG to XML. returns name of node, for end tag -- if empty, then children will not be output.

func SVGNodeTreeMarshalXML added in v1.2.0

func SVGNodeTreeMarshalXML(itm ki.Ki, enc *XMLEncoder, setName string) (string, error)

SVGNodeTreeMarshalXML encodes item and any children to XML. returns any error, and name of element that enc.WriteEnd() should be called with -- allows for extra elements to be added at end of list.

func SVGNodeXMLGrad added in v1.2.0

func SVGNodeXMLGrad(nd *gi.Gradient, name string, enc *XMLEncoder)

func SetFloat32SliceLen added in v1.2.0

func SetFloat32SliceLen(dat *[]float32, sz int)

SetFloat32SliceLen is a utility function to set given slice of float32 values to given length, reusing existing where possible and making a new one as needed. For use in WriteGeom routines.

func SetUnitContext added in v1.1.0

func SetUnitContext(pc *gist.Paint, vp *gi.Viewport2D, el mat32.Vec2)

SetUnitContext sets the unit context based on size of viewport and parent element (from bbox) and then cache everything out in terms of raw pixel dots for rendering -- call at start of render

func SplitNameId added in v1.2.0

func SplitNameId(elnm, nm string) (bool, int)

SplitNameId splits name after the element name (e.g., 'rect') returning true if it starts with element name, and numerical id part after that element. if numerical id part is 0, then it didn't parse. SVG object names are element names + numerical id

func SplitNameIdDig added in v1.2.3

func SplitNameIdDig(nm string) (string, int)

SplitNameIdDig splits name into numerical end part and preceding name, based on string of digits from end of name. If Id == 0 then it was not specified or didn't parse. SVG object names are element names + numerical id

func StyleCSS

func StyleCSS(node gi.Node2D, css ki.Props)

StyleCSS applies css style properties to given SVG node, parsing out type, .class, and #name selectors

func StyleSVG

func StyleSVG(gii gi.Node2D)

StyleSVG styles the Paint values directly from node properties -- no relevant default styling here -- parents can just set props directly as needed

func UpdateGradientStops added in v1.2.0

func UpdateGradientStops(gr *gi.Gradient)

UpdateGradientStops copies stops from StopsName gradient if it is set

func UpdateNodeGradientPoints added in v1.2.3

func UpdateNodeGradientPoints(gii gi.Node2D, prop string)

UpdateNodeGradientPoints updates the points for node based on current bbox

func UpdateNodeGradientProp added in v1.2.3

func UpdateNodeGradientProp(gii gi.Node2D, prop string, radial bool, stops string) (*gi.Gradient, string)

UpdateNodeGradientProp ensures that node has a gradient property of given type

func XMLAddAttr added in v1.2.0

func XMLAddAttr(attr *[]xml.Attr, name, val string)

Types

type Circle

type Circle struct {
	NodeBase
	Pos    mat32.Vec2 `xml:"{cx,cy}" desc:"position of the center of the circle"`
	Radius float32    `xml:"r" desc:"radius of the circle"`
}

Circle is a SVG circle

func AddNewCircle added in v0.9.7

func AddNewCircle(parent ki.Ki, name string, x, y, radius float32) *Circle

AddNewCircle adds a new button to given parent node, with given name, x,y pos, and radius.

func (*Circle) ApplyDeltaXForm added in v1.2.0

func (g *Circle) ApplyDeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2)

ApplyDeltaXForm applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Circle) ApplyXForm added in v1.2.0

func (g *Circle) ApplyXForm(xf mat32.Mat2)

ApplyXForm applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Circle) CopyFieldsFrom added in v0.9.8

func (g *Circle) CopyFieldsFrom(frm interface{})

func (*Circle) ReadGeom added in v1.2.0

func (g *Circle) ReadGeom(dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Circle) Render2D

func (g *Circle) Render2D()

func (*Circle) SVGLocalBBox added in v1.2.3

func (g *Circle) SVGLocalBBox() mat32.Box2

func (*Circle) SVGName added in v1.2.0

func (g *Circle) SVGName() string

func (*Circle) SetPos added in v1.2.3

func (g *Circle) SetPos(pos mat32.Vec2)

func (*Circle) SetSize added in v1.2.3

func (g *Circle) SetSize(sz mat32.Vec2)

func (*Circle) WriteGeom added in v1.2.0

func (g *Circle) WriteGeom(dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type ClipPath

type ClipPath struct {
	NodeBase
}

ClipPath is used for holding a path that renders as a clip path

func AddNewClipPath added in v0.9.7

func AddNewClipPath(parent ki.Ki, name string) *ClipPath

AddNewClipPath adds a new clippath to given parent node, with given name.

func (*ClipPath) CopyFieldsFrom added in v0.9.8

func (g *ClipPath) CopyFieldsFrom(frm interface{})

func (*ClipPath) SVGName added in v1.2.0

func (g *ClipPath) SVGName() string

type Editor

type Editor struct {
	SVG
	Trans         mat32.Vec2 `desc:"view translation offset (from dragging)"`
	Scale         float32    `desc:"view scaling (from zooming)"`
	SetDragCursor bool       `view:"-" desc:"has dragging cursor been set yet?"`
}

Editor supports editing of SVG elements

func AddNewEditor added in v0.9.7

func AddNewEditor(parent ki.Ki, name string) *Editor

AddNewEditor adds a new editor to given parent node, with given name.

func (*Editor) ConnectEvents2D added in v0.9.8

func (svg *Editor) ConnectEvents2D()

func (*Editor) CopyFieldsFrom added in v0.9.8

func (g *Editor) CopyFieldsFrom(frm interface{})

func (*Editor) EditorEvents

func (svg *Editor) EditorEvents()

EditorEvents handles svg editing events

func (*Editor) InitScale

func (svg *Editor) InitScale()

InitScale ensures that Scale is initialized and non-zero

func (*Editor) Render2D

func (svg *Editor) Render2D()

func (*Editor) SetTransform

func (svg *Editor) SetTransform()

SetTransform sets the transform based on Trans and Scale values

type Ellipse

type Ellipse struct {
	NodeBase
	Pos   mat32.Vec2 `xml:"{cx,cy}" desc:"position of the center of the ellipse"`
	Radii mat32.Vec2 `xml:"{rx,ry}" desc:"radii of the ellipse in the horizontal, vertical axes"`
}

Ellipse is a SVG ellipse

func AddNewEllipse added in v0.9.7

func AddNewEllipse(parent ki.Ki, name string, x, y, rx, ry float32) *Ellipse

AddNewEllipse adds a new button to given parent node, with given name, pos and radii.

func (*Ellipse) ApplyDeltaXForm added in v1.2.0

func (g *Ellipse) ApplyDeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2)

ApplyDeltaXForm applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Ellipse) ApplyXForm added in v1.2.0

func (g *Ellipse) ApplyXForm(xf mat32.Mat2)

ApplyXForm applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Ellipse) CopyFieldsFrom added in v0.9.8

func (g *Ellipse) CopyFieldsFrom(frm interface{})

func (*Ellipse) ReadGeom added in v1.2.0

func (g *Ellipse) ReadGeom(dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Ellipse) Render2D

func (g *Ellipse) Render2D()

func (*Ellipse) SVGLocalBBox added in v1.2.3

func (g *Ellipse) SVGLocalBBox() mat32.Box2

func (*Ellipse) SVGName added in v1.2.0

func (g *Ellipse) SVGName() string

func (*Ellipse) SetPos added in v1.2.3

func (g *Ellipse) SetPos(pos mat32.Vec2)

func (*Ellipse) SetSize added in v1.2.3

func (g *Ellipse) SetSize(sz mat32.Vec2)

func (*Ellipse) WriteGeom added in v1.2.0

func (g *Ellipse) WriteGeom(dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type Filter

type Filter struct {
	NodeBase
	FilterType string
}

Filter represents SVG filter* elements

func AddNewFilter added in v0.9.7

func AddNewFilter(parent ki.Ki, name string) *Filter

AddNewFilter adds a new filter to given parent node, with given name.

func (*Filter) CopyFieldsFrom added in v0.9.8

func (g *Filter) CopyFieldsFrom(frm interface{})

func (*Filter) SVGName added in v1.2.0

func (g *Filter) SVGName() string

type Flow

type Flow struct {
	NodeBase
	FlowType string
}

Flow represents SVG flow* elements

func AddNewFlow added in v0.9.7

func AddNewFlow(parent ki.Ki, name string) *Flow

AddNewFlow adds a new flow to given parent node, with given name.

func (*Flow) CopyFieldsFrom added in v0.9.8

func (g *Flow) CopyFieldsFrom(frm interface{})

func (*Flow) SVGName added in v1.2.0

func (g *Flow) SVGName() string

type Group

type Group struct {
	NodeBase
}

Group groups together SVG elements -- doesn't do much but provide a locus for properties etc

func AddNewGroup added in v0.9.7

func AddNewGroup(parent ki.Ki, name string) *Group

AddNewGroup adds a new group to given parent node, with given name.

func (*Group) ApplyDeltaXForm added in v1.2.3

func (g *Group) ApplyDeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2)

ApplyDeltaXForm applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Group) ApplyXForm added in v1.2.3

func (g *Group) ApplyXForm(xf mat32.Mat2)

ApplyXForm applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Group) BBox2D

func (g *Group) BBox2D() image.Rectangle

func (*Group) CopyFieldsFrom added in v0.9.8

func (g *Group) CopyFieldsFrom(frm interface{})

func (*Group) EnforceSVGName added in v1.2.3

func (g *Group) EnforceSVGName() bool

func (*Group) ReadGeom added in v1.2.3

func (g *Group) ReadGeom(dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Group) Render2D

func (g *Group) Render2D()

func (*Group) SVGName added in v1.2.0

func (g *Group) SVGName() string

func (*Group) WriteGeom added in v1.2.3

func (g *Group) WriteGeom(dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type Icon

type Icon struct {
	SVG
	Filename string      `desc:"file name with full path for icon if loaded from file"`
	Rendered bool        `` /* 169-byte string literal not displayed */
	RendSize image.Point `copy:"-" json:"-" xml:"-" desc:"size at which we previously rendered"`
}

svg.Icon is the actual SVG for a gi.Icon -- it should contain no color information -- it should just be a filled shape where the fill and stroke colors come from the surrounding context / paint settings. The rendered version is cached for a given size. Icons are always copied from an original source icon and then can be customized from there.

func AddNewIcon added in v0.9.7

func AddNewIcon(parent ki.Ki, name string) *Icon

AddNewIcon adds a new icon to given parent node, with given name.

func (*Icon) CopyFieldsFrom added in v0.9.8

func (ic *Icon) CopyFieldsFrom(frm interface{})

func (*Icon) CopyFromIcon

func (ic *Icon) CopyFromIcon(cp *Icon)

CopyFromIcon copies from a source icon, typically one from a library -- preserves all the existing render state etc for the current icon, so that only a new render is required

func (*Icon) Init2D

func (ic *Icon) Init2D()

func (*Icon) Layout2D

func (ic *Icon) Layout2D(parBBox image.Rectangle, iter int) bool

func (*Icon) NeedsReRender

func (ic *Icon) NeedsReRender() bool

NeedsReRender tests whether the last render parameters (size, color) have changed or not

func (*Icon) Render2D

func (ic *Icon) Render2D()

func (*Icon) Size2D

func (ic *Icon) Size2D(iter int)

type IconMgr

type IconMgr struct {
}

svg.IconMgr is THE implementation of the gi.IconMgr interface

func (*IconMgr) IconByName

func (im *IconMgr) IconByName(name string) (ki.Ki, error)

IconByName is main function to get icon by name -- looks in CurIconSet and falls back to DefaultIconSet if not found there -- returns error message if not found. cast result to *svg.Icon

func (*IconMgr) IconList

func (im *IconMgr) IconList(alphaSort bool) []gi.IconName

IconList returns the current list of all available icons, optionally sorted in alphabetical order.

func (*IconMgr) IsValid

func (im *IconMgr) IsValid(iconName string) bool

func (*IconMgr) SetIcon

func (im *IconMgr) SetIcon(ic *gi.Icon, iconName string) error

SetIcon sets the icon by name into given Icon wrapper, returning error message if not found etc. This is how gi.Icon is initialized from underlying svg.Icon items.

type IconSet

type IconSet map[string]*Icon

IconSet is a collection of icons

var CurIconSet IconSet

CurIconSet is the current icon set -- defaults to default but can be changed to whatever you want

var DefaultIconSet IconSet

DefaultIconSet is the default icon set, initialized by default

func MakeDefaultIcons

func MakeDefaultIcons() IconSet

func (*IconSet) IconList

func (iset *IconSet) IconList(alphaSort bool) []gi.IconName

IconList returns a list of names of icons in the icon set

func (*IconSet) OpenDefaultIcons

func (iset *IconSet) OpenDefaultIcons() error

func (*IconSet) OpenIconsFromAssetDir added in v0.9.9

func (iset *IconSet) OpenIconsFromAssetDir(path string, dirFunc func(path string) ([]string, error), assetFunc func(name string) ([]byte, error)) error

OpenIconsFromAssetDir loads icons using Asset and AssetDir funcs as generated by e.g., https://github.com/shuLhan/go-bindata or similar such forks of go-bindata

func (*IconSet) OpenIconsFromPath

func (iset *IconSet) OpenIconsFromPath(path string) error

OpenIconsFromPath scans for .svg icon files in given path, adding them to the given IconSet, just storing the filename for later lazy loading

type Image added in v1.2.0

type Image struct {
	NodeBase
	Pos                 mat32.Vec2  `xml:"{x,y}" desc:"position of the top-left of the image"`
	Size                mat32.Vec2  `xml:"{width,height}" desc:"rendered size of the image (imposes a scaling on image when it is rendered)"`
	PreserveAspectRatio bool        `xml:"preserveAspectRatio" desc:"directs resize operations to preserve aspect ratio"`
	Filename            gi.FileName `desc:"file name of image loaded -- set by OpenImage"`
	Pixels              *image.RGBA `copy:"-" xml:"-" json:"-" view:"-" desc:"the image pixels"`
}

Image is an SVG image (bitmap)

func AddNewImage added in v1.2.0

func AddNewImage(parent ki.Ki, name string, x, y float32) *Image

AddNewImage adds a new image to given parent node, with given name and pos

func (*Image) ApplyDeltaXForm added in v1.2.0

func (g *Image) ApplyDeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2)

ApplyDeltaXForm applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Image) ApplyXForm added in v1.2.0

func (g *Image) ApplyXForm(xf mat32.Mat2)

ApplyXForm applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Image) BBox2D added in v1.2.0

func (g *Image) BBox2D() image.Rectangle

func (*Image) CopyFieldsFrom added in v1.2.0

func (g *Image) CopyFieldsFrom(frm interface{})

func (*Image) DrawImage added in v1.2.0

func (g *Image) DrawImage()

func (*Image) OpenImage added in v1.2.0

func (g *Image) OpenImage(filename gi.FileName, width, height float32) error

OpenImage opens an image for the bitmap, and resizes to the size of the image or the specified size -- pass 0 for width and/or height to use the actual image size for that dimension

func (*Image) ReadGeom added in v1.2.0

func (g *Image) ReadGeom(dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Image) Render2D added in v1.2.0

func (g *Image) Render2D()

func (*Image) SVGLocalBBox added in v1.2.5

func (g *Image) SVGLocalBBox() mat32.Box2

func (*Image) SVGName added in v1.2.0

func (g *Image) SVGName() string

func (*Image) SaveImage added in v1.2.3

func (g *Image) SaveImage(filename gi.FileName) error

SaveImage saves current image to a file

func (*Image) SetImage added in v1.2.0

func (g *Image) SetImage(img image.Image, width, height float32)

SetImage sets an image for the bitmap , and resizes to the size of the image or the specified size -- pass 0 for width and/or height to use the actual image size for that dimension. Copies from given image into internal image for this bitmap.

func (*Image) SetImageSize added in v1.2.3

func (g *Image) SetImageSize(nwsz image.Point)

SetImageSize sets size of the bitmap image. This does not resize any existing image, just makes a new image if the size is different

func (*Image) SetPos added in v1.2.3

func (g *Image) SetPos(pos mat32.Vec2)

func (*Image) SetSize added in v1.2.0

func (g *Image) SetSize(sz mat32.Vec2)

func (*Image) WriteGeom added in v1.2.0

func (g *Image) WriteGeom(dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type Line

type Line struct {
	NodeBase
	Start mat32.Vec2 `xml:"{x1,y1}" desc:"position of the start of the line"`
	End   mat32.Vec2 `xml:"{x2,y2}" desc:"position of the end of the line"`
}

Line is a SVG line

func AddNewLine added in v0.9.7

func AddNewLine(parent ki.Ki, name string, sx, sy, ex, ey float32) *Line

AddNewLine adds a new line to given parent node, with given name, st and end.

func (*Line) ApplyDeltaXForm added in v1.2.0

func (g *Line) ApplyDeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2)

ApplyDeltaXForm applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Line) ApplyXForm added in v1.2.0

func (g *Line) ApplyXForm(xf mat32.Mat2)

ApplyXForm applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Line) CopyFieldsFrom added in v0.9.8

func (g *Line) CopyFieldsFrom(frm interface{})

func (*Line) ReadGeom added in v1.2.0

func (g *Line) ReadGeom(dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Line) Render2D

func (g *Line) Render2D()

func (*Line) SVGLocalBBox added in v1.2.5

func (g *Line) SVGLocalBBox() mat32.Box2

func (*Line) SVGName added in v1.2.0

func (g *Line) SVGName() string

func (*Line) SetPos added in v1.2.3

func (g *Line) SetPos(pos mat32.Vec2)

func (*Line) SetSize added in v1.2.3

func (g *Line) SetSize(sz mat32.Vec2)

func (*Line) WriteGeom added in v1.2.0

func (g *Line) WriteGeom(dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type Marker

type Marker struct {
	NodeBase
	RefPos      mat32.Vec2  `xml:"{refX,refY}" desc:"reference position to align the vertex position with, specified in ViewBox coordinates"`
	Size        mat32.Vec2  `xml:"{markerWidth,markerHeight}" desc:"size of marker to render, in Units units"`
	Units       MarkerUnits `xml:"markerUnits" desc:"units to use"`
	ViewBox     ViewBox     `desc:"viewbox defines the internal coordinate system for the drawing elements within the marker"`
	Orient      string      `xml:"orient" desc:"orientation of the marker -- either 'auto' or an angle"`
	VertexPos   mat32.Vec2  `desc:"current vertex position"`
	VertexAngle float32     `desc:"current vertex angle in radians"`
	StrokeWidth float32     `desc:"current stroke width"`
	XForm       mat32.Mat2  `desc:"net transform computed from settings and current values -- applied prior to rendering"`
	EffSize     mat32.Vec2  `desc:"effective size for actual rendering"`
}

Marker represents marker elements that can be drawn along paths (arrow heads, etc)

func AddNewMarker added in v0.9.7

func AddNewMarker(parent ki.Ki, name string) *Marker

AddNewMarker adds a new marker to given parent node, with given name.

func MarkerByName added in v1.2.0

func MarkerByName(gii gi.Node2D, marker string) *Marker

MarkerByName finds marker property of given name, or generic "marker" type, and if set, attempts to find that marker and return it

func (*Marker) ComputeBBoxSVG added in v1.2.17

func (g *Marker) ComputeBBoxSVG()

func (*Marker) CopyFieldsFrom added in v0.9.8

func (g *Marker) CopyFieldsFrom(frm interface{})

func (*Marker) EnforceSVGName added in v1.2.3

func (g *Marker) EnforceSVGName() bool

func (*Marker) Render2D added in v1.2.5

func (g *Marker) Render2D()

func (*Marker) RenderMarker

func (mrk *Marker) RenderMarker(vertexPos mat32.Vec2, vertexAng, strokeWidth float32)

RenderMarker renders the marker using given vertex position, angle (in radians), and stroke width

func (*Marker) SVGName added in v1.2.0

func (g *Marker) SVGName() string

type MarkerUnits

type MarkerUnits int32

MarkerUnits specifies units to use for svg marker elements

const (
	StrokeWidth MarkerUnits = iota
	UserSpaceOnUse
	MarkerUnitsN
)

func (*MarkerUnits) FromString

func (i *MarkerUnits) FromString(s string) error

func (MarkerUnits) MarshalJSON

func (ev MarkerUnits) MarshalJSON() ([]byte, error)

func (MarkerUnits) String

func (i MarkerUnits) String() string

func (*MarkerUnits) UnmarshalJSON

func (ev *MarkerUnits) UnmarshalJSON(b []byte) error

type NodeBase

type NodeBase struct {
	gi.Node2DBase
	Pnt girl.Paint `json:"-" xml:"-" desc:"full paint information for this node"`
}

svg.NodeBase is an element within the SVG sub-scenegraph -- does not use layout logic -- just renders into parent SVG viewport

func (*NodeBase) ApplyDeltaXForm added in v1.2.0

func (g *NodeBase) ApplyDeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2)

ApplyDeltaXForm applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*NodeBase) ApplyXForm added in v1.2.0

func (g *NodeBase) ApplyXForm(xf mat32.Mat2)

ApplyXForm applies the given 2D transform to the geometry of this node this just does a direct transform multiplication on coordinates.

func (*NodeBase) AsSVGNode

func (g *NodeBase) AsSVGNode() *NodeBase

func (*NodeBase) BBox2D

func (g *NodeBase) BBox2D() image.Rectangle

func (*NodeBase) BaseIface added in v1.2.0

func (n *NodeBase) BaseIface() reflect.Type

func (*NodeBase) ChildrenBBox2D

func (g *NodeBase) ChildrenBBox2D() image.Rectangle

func (*NodeBase) ComputeBBox2D

func (g *NodeBase) ComputeBBox2D(parBBox image.Rectangle, delta image.Point)

func (*NodeBase) ComputeBBoxSVG

func (g *NodeBase) ComputeBBoxSVG()

ComputeBBoxSVG is called by default in render to compute bounding boxes for gui interaction -- can only be done in rendering because that is when all the proper xforms are all in place -- VpBBox is intersected with parent SVG

func (*NodeBase) CopyFieldsFrom added in v0.9.8

func (g *NodeBase) CopyFieldsFrom(frm interface{})

func (*NodeBase) DeltaXForm added in v1.2.0

func (g *NodeBase) DeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2, self bool) (mat32.Mat2, mat32.Vec2)

DeltaXForm computes the net transform matrix for given delta xform parameters and the transformed version of the reference point. If self is true, then include the current node self transform, otherwise don't. Groups do not but regular rendering nodes do.

func (*NodeBase) EnforceSVGName added in v1.2.3

func (g *NodeBase) EnforceSVGName() bool

func (*NodeBase) GradientApplyXForm added in v1.2.0

func (g *NodeBase) GradientApplyXForm(xf mat32.Mat2)

GradientApplyXForm applies the given transform to any gradients for this node, that are using specific coordinates (not bounding box which is automatic)

func (*NodeBase) GradientApplyXFormPt added in v1.2.0

func (g *NodeBase) GradientApplyXFormPt(xf mat32.Mat2, pt mat32.Vec2)

GradientApplyXFormPt applies the given transform with ctr point to any gradients for this node, that are using specific coordinates (not bounding box which is automatic)

func (*NodeBase) GradientReadPts added in v1.2.0

func (g *NodeBase) GradientReadPts(dat []float32)

GradientReadPts reads the geometry of the gradients for this node from a slice of floating point numbers, reading from the end.

func (*NodeBase) GradientWritePts added in v1.2.0

func (g *NodeBase) GradientWritePts(dat *[]float32)

GradientWritePts writes the geometry of the gradients for this node to a slice of floating point numbers, appending to end of slice.

func (*NodeBase) Init2D

func (g *NodeBase) Init2D()

func (*NodeBase) Init2DBase

func (g *NodeBase) Init2DBase()

Init2DBase handles basic node initialization -- Init2D can then do special things

func (*NodeBase) Layout2D

func (g *NodeBase) Layout2D(parBBox image.Rectangle, iter int) bool

func (*NodeBase) LocalBBoxToWin added in v1.2.5

func (g *NodeBase) LocalBBoxToWin(bb mat32.Box2) image.Rectangle

LocalBBoxToWin converts a local bounding box to Window coordinates

func (*NodeBase) LocalLineWidth added in v1.2.5

func (g *NodeBase) LocalLineWidth() float32

LocalLineWidth returns the line width in local coordinates

func (*NodeBase) Move2D

func (g *NodeBase) Move2D(delta image.Point, parBBox image.Rectangle)

func (*NodeBase) Paint

func (g *NodeBase) Paint() *gist.Paint

Paint satisfies the painter interface

func (*NodeBase) ParXForm added in v1.2.3

func (g *NodeBase) ParXForm(self bool) mat32.Mat2

ParXForm returns the full compounded 2D transform matrix for all of the parents of this node. If self is true, then include our own xform too.

func (*NodeBase) PushXForm added in v1.2.5

func (g *NodeBase) PushXForm() (bool, *girl.State)

PushXForm checks our bounding box and visibility, returning false if out of bounds. If visible, pushes our xform. Must be called as first step in Render2D.

func (*NodeBase) ReadGeom added in v1.2.0

func (g *NodeBase) ReadGeom(dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*NodeBase) ReadXForm added in v1.2.3

func (g *NodeBase) ReadXForm(dat []float32, idx int)

ReadXForm reads the node transform from slice at starting index.

func (*NodeBase) Render2D

func (g *NodeBase) Render2D()

func (*NodeBase) SVGLocalBBox added in v1.2.3

func (g *NodeBase) SVGLocalBBox() mat32.Box2

func (*NodeBase) SVGName added in v1.2.0

func (g *NodeBase) SVGName() string

func (*NodeBase) SetColorProps added in v1.2.3

func (g *NodeBase) SetColorProps(prop, color string)

SetColorProps sets color property from a string representation. It breaks color alpha out as opacity. prop is either "stroke" or "fill"

func (*NodeBase) SetPos added in v1.2.3

func (g *NodeBase) SetPos(pos mat32.Vec2)

func (*NodeBase) SetSize added in v1.2.3

func (g *NodeBase) SetSize(sz mat32.Vec2)

func (*NodeBase) Size2D

func (g *NodeBase) Size2D(iter int)

func (*NodeBase) Style2D

func (g *NodeBase) Style2D()

func (*NodeBase) WriteGeom added in v1.2.0

func (g *NodeBase) WriteGeom(dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

func (*NodeBase) WriteXForm added in v1.2.3

func (g *NodeBase) WriteXForm(dat []float32, idx int)

WriteXForm writes the node transform to slice at starting index. slice must already be allocated sufficiently.

type NodeSVG added in v1.2.0

type NodeSVG interface {
	gi.Node2D

	// AsSVGNode returns a generic svg.NodeBase for our node -- gives generic
	// access to all the base-level data structures without requiring
	// interface methods.
	AsSVGNode() *NodeBase

	// SetPos sets the *upper left* position of this element, in local dimensions
	SetPos(pos mat32.Vec2)

	// SetSize sets the overall size of this element, in local dimensions
	SetSize(sz mat32.Vec2)

	// SVGLocalBBox returns the bounding box of node in local dimensions
	SVGLocalBBox() mat32.Box2

	// ApplyXForm applies the given 2D transform to the geometry of this node
	// this just does a direct transform multiplication on coordinates.
	ApplyXForm(xf mat32.Mat2)

	// ApplyDeltaXForm applies the given 2D delta transforms to the geometry of this node
	// relative to given point.  Trans translation and point are in top-level coordinates,
	// so must be transformed into local coords first.
	// Point is upper left corner of selection box that anchors the translation and scaling,
	// and for rotation it is the center point around which to rotate
	ApplyDeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2)

	// WriteGeom writes the geometry of the node to a slice of floating point numbers
	// the length and ordering of which is specific to each node type.
	// Slice must be passed and will be resized if not the correct length.
	WriteGeom(dat *[]float32)

	// ReadGeom reads the geometry of the node from a slice of floating point numbers
	// the length and ordering of which is specific to each node type.
	ReadGeom(dat []float32)

	// SVGName returns the SVG element name (e.g., "rect", "path" etc)
	SVGName() string

	// EnforceSVGName returns true if in general this element should
	// be named with its SVGName plus a unique id.
	// Groups and Markers are false.
	EnforceSVGName() bool
}

NodeSVG is the interface for all SVG nodes, based on gi.Node2D

type Path

type Path struct {
	NodeBase
	Data    []PathData `` /* 171-byte string literal not displayed */
	DataStr string     `xml:"d" desc:"string version of the path data"`
}

Path renders SVG data sequences that can render just about anything

func AddNewPath added in v0.9.7

func AddNewPath(parent ki.Ki, name string, data string) *Path

AddNewPath adds a new button to given parent node, with given name and path data.

func (*Path) ApplyDeltaXForm added in v1.2.0

func (g *Path) ApplyDeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2)

ApplyDeltaXForm applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Path) ApplyXForm added in v1.2.0

func (g *Path) ApplyXForm(xf mat32.Mat2)

ApplyXForm applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Path) ApplyXFormImpl added in v1.2.0

func (g *Path) ApplyXFormImpl(xf mat32.Mat2, lpt mat32.Vec2)

ApplyXFormImpl does the implementation of applying a transform to all points

func (*Path) CopyFieldsFrom added in v0.9.8

func (g *Path) CopyFieldsFrom(frm interface{})

func (*Path) ReadGeom added in v1.2.0

func (g *Path) ReadGeom(dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Path) Render2D

func (g *Path) Render2D()

func (*Path) SVGLocalBBox added in v1.2.5

func (g *Path) SVGLocalBBox() mat32.Box2

func (*Path) SVGName added in v1.2.0

func (g *Path) SVGName() string

func (*Path) SetData

func (g *Path) SetData(data string) error

SetData sets the path data to given string, parsing it into an optimized form used for rendering

func (*Path) SetPos added in v1.2.3

func (g *Path) SetPos(pos mat32.Vec2)

func (*Path) SetSize added in v1.2.3

func (g *Path) SetSize(sz mat32.Vec2)

func (*Path) WriteGeom added in v1.2.0

func (g *Path) WriteGeom(dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type PathCmds

type PathCmds byte

PathCmds are the commands within the path SVG drawing data type

const (
	// move pen, abs coords
	PcM PathCmds = iota
	// move pen, rel coords
	Pcm
	// lineto, abs
	PcL
	// lineto, rel
	Pcl
	// horizontal lineto, abs
	PcH
	// relative lineto, rel
	Pch
	// vertical lineto, abs
	PcV
	// vertical lineto, rel
	Pcv
	// Bezier curveto, abs
	PcC
	// Bezier curveto, rel
	Pcc
	// smooth Bezier curveto, abs
	PcS
	// smooth Bezier curveto, rel
	Pcs
	// quadratic Bezier curveto, abs
	PcQ
	// quadratic Bezier curveto, rel
	Pcq
	// smooth quadratic Bezier curveto, abs
	PcT
	// smooth quadratic Bezier curveto, rel
	Pct
	// elliptical arc, abs
	PcA
	// elliptical arc, rel
	Pca
	// close path
	PcZ
	// close path
	Pcz
	// error -- invalid command
	PcErr
)

func PathDataNextCmd

func PathDataNextCmd(data []PathData, i *int) (PathCmds, int)

PathDataNextCmd gets the next path data command, incrementing the index -- ++ not an expression so its clunky

func PathDecodeCmd

func PathDecodeCmd(r rune) PathCmds

PathDecodeCmd decodes rune into corresponding command

func (PathCmds) EncCmd

func (pc PathCmds) EncCmd(n int) PathData

EncCmd encodes command and n into PathData

func (*PathCmds) FromString

func (i *PathCmds) FromString(s string) error

func (PathCmds) MarshalJSON

func (ev PathCmds) MarshalJSON() ([]byte, error)

func (PathCmds) String

func (i PathCmds) String() string

func (*PathCmds) UnmarshalJSON

func (ev *PathCmds) UnmarshalJSON(b []byte) error

type PathData

type PathData float32

PathData encodes the svg path data, using 32-bit floats which are converted into uint32 for path commands, and contain the command as the first 5 bits, and the remaining 27 bits are the number of data points following the path command to interpret as numbers.

func PathDataParse

func PathDataParse(d string) ([]PathData, error)

PathDataParse parses a string representation of the path data into compiled path data

func (PathData) Cmd

func (pd PathData) Cmd() (PathCmds, int)

Cmd decodes path data as a command and a number of subsequent values for that command

type Polygon

type Polygon struct {
	Polyline
}

Polygon is a SVG polygon

func AddNewPolygon added in v0.9.7

func AddNewPolygon(parent ki.Ki, name string, points []mat32.Vec2) *Polygon

AddNewPolygon adds a new polygon to given parent node, with given name and points.

func (*Polygon) Render2D

func (g *Polygon) Render2D()

func (*Polygon) SVGName added in v1.2.0

func (g *Polygon) SVGName() string

type Polyline

type Polyline struct {
	NodeBase
	Points []mat32.Vec2 `xml:"points" desc:"the coordinates to draw -- does a moveto on the first, then lineto for all the rest"`
}

Polyline is a SVG multi-line shape

func AddNewPolyline added in v0.9.7

func AddNewPolyline(parent ki.Ki, name string, points []mat32.Vec2) *Polyline

AddNewPolyline adds a new polyline to given parent node, with given name and points.

func (*Polyline) ApplyDeltaXForm added in v1.2.0

func (g *Polyline) ApplyDeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2)

ApplyDeltaXForm applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Polyline) ApplyXForm added in v1.2.0

func (g *Polyline) ApplyXForm(xf mat32.Mat2)

ApplyXForm applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Polyline) CopyFieldsFrom added in v0.9.8

func (g *Polyline) CopyFieldsFrom(frm interface{})

func (*Polyline) ReadGeom added in v1.2.0

func (g *Polyline) ReadGeom(dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Polyline) Render2D

func (g *Polyline) Render2D()

func (*Polyline) SVGLocalBBox added in v1.2.5

func (g *Polyline) SVGLocalBBox() mat32.Box2

func (*Polyline) SVGName added in v1.2.0

func (g *Polyline) SVGName() string

func (*Polyline) SetPos added in v1.2.3

func (g *Polyline) SetPos(pos mat32.Vec2)

func (*Polyline) SetSize added in v1.2.3

func (g *Polyline) SetSize(sz mat32.Vec2)

func (*Polyline) WriteGeom added in v1.2.0

func (g *Polyline) WriteGeom(dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type Rect

type Rect struct {
	NodeBase
	Pos    mat32.Vec2 `xml:"{x,y}" desc:"position of the top-left of the rectangle"`
	Size   mat32.Vec2 `xml:"{width,height}" desc:"size of the rectangle"`
	Radius mat32.Vec2 `xml:"{rx,ry}" desc:"radii for curved corners, as a proportion of width, height"`
}

Rect is a SVG rectangle, optionally with rounded corners

func AddNewRect added in v0.9.7

func AddNewRect(parent ki.Ki, name string, x, y, sx, sy float32) *Rect

AddNewRect adds a new rectangle to given parent node, with given name, pos, and size.

func (*Rect) ApplyDeltaXForm added in v1.2.0

func (g *Rect) ApplyDeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2)

ApplyDeltaXForm applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Rect) ApplyXForm added in v1.2.0

func (g *Rect) ApplyXForm(xf mat32.Mat2)

ApplyXForm applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Rect) CopyFieldsFrom added in v0.9.8

func (g *Rect) CopyFieldsFrom(frm interface{})

func (*Rect) ReadGeom added in v1.2.0

func (g *Rect) ReadGeom(dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Rect) Render2D

func (g *Rect) Render2D()

func (*Rect) SVGLocalBBox added in v1.2.3

func (g *Rect) SVGLocalBBox() mat32.Box2

func (*Rect) SVGName added in v1.2.0

func (g *Rect) SVGName() string

func (*Rect) SetPos added in v1.2.3

func (g *Rect) SetPos(pos mat32.Vec2)

func (*Rect) SetSize added in v1.2.3

func (g *Rect) SetSize(sz mat32.Vec2)

func (*Rect) WriteGeom added in v1.2.0

func (g *Rect) WriteGeom(dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type SVG

type SVG struct {
	gi.Viewport2D
	ViewBox    ViewBox          `` /* 147-byte string literal not displayed */
	PhysWidth  units.Value      `desc:"physical width of the drawing, e.g., when printed -- does not affect rendering -- metadata"`
	PhysHeight units.Value      `desc:"physical height of the drawing, e.g., when printed -- does not affect rendering -- metadata"`
	Norm       bool             `` /* 130-byte string literal not displayed */
	InvertY    bool             `` /* 181-byte string literal not displayed */
	Pnt        girl.Paint       `json:"-" xml:"-" desc:"paint styles -- inherited by nodes"`
	Defs       Group            `desc:"all defs defined elements go here (gradients, symbols, etc)"`
	Title      string           `xml:"title" desc:"the title of the svg"`
	Desc       string           `xml:"desc" desc:"the description of the svg"`
	DefIdxs    map[string]int   `` /* 133-byte string literal not displayed */
	UniqueIds  map[int]struct{} `` /* 179-byte string literal not displayed */
}

SVG is a viewport for containing SVG drawing objects, corresponding to the svg tag in html -- it provides its own bitmap for drawing into. To trigger a full re-render of SVG, do SetNeedsFullRender() in UpdateStart / End loop.

func AddNewSVG added in v0.9.7

func AddNewSVG(parent ki.Ki, name string) *SVG

AddNewSVG adds a new svg viewport to given parent node, with given name.

func ParentSVG added in v1.2.0

func ParentSVG(g *gi.Node2DBase) *SVG

ParentSVG returns the parent SVG viewport

func (*SVG) AddNewGradient added in v1.2.3

func (sv *SVG) AddNewGradient(radial bool) (*gi.Gradient, string)

AddNewGradient adds a new gradient, either linear or radial, with a new unique id

func (*SVG) ConnectEvents2D added in v1.2.2

func (sv *SVG) ConnectEvents2D()

func (*SVG) ContextColorSpecByURL added in v1.2.0

func (sv *SVG) ContextColorSpecByURL(url string) *gist.ColorSpec

ContextColorSpecByURL finds a Node by an element name (URL-like path), and attempts to convert it to a Gradient -- if successful, returns ColorSpec on that. Used for colorspec styling based on url() value.

func (*SVG) CopyFieldsFrom added in v0.9.8

func (sv *SVG) CopyFieldsFrom(frm interface{})

func (*SVG) DeleteAll

func (sv *SVG) DeleteAll()

DeleteAll deletes any existing elements in this svg

func (*SVG) FindDefByName added in v1.2.0

func (sv *SVG) FindDefByName(defnm string) gi.Node2D

FindDefByName finds Defs item by name, using cached indexes for speed

func (*SVG) FindNamedElement

func (sv *SVG) FindNamedElement(name string) gi.Node2D

func (*SVG) GatherIds added in v1.2.0

func (sv *SVG) GatherIds()

GatherIds gathers all the numeric id suffixes currently in use. It automatically renames any that are not unique or empty.

func (*SVG) Init2D

func (sv *SVG) Init2D()

func (*SVG) IsRendering added in v1.2.2

func (sv *SVG) IsRendering() bool

IsRendering returns true if the SVG is currently rendering

func (*SVG) Layout2D

func (sv *SVG) Layout2D(parBBox image.Rectangle, iter int) bool

func (*SVG) MarshalXMLx added in v1.2.0

func (sv *SVG) MarshalXMLx(enc *XMLEncoder, se xml.StartElement) error

MarshalXMLx marshals the svg using XMLEncoder

func (*SVG) NewUniqueId added in v1.2.0

func (sv *SVG) NewUniqueId() int

NewUniqueId returns a new unique numerical id number, for naming an object

func (*SVG) NodeEnsureUniqueId added in v1.2.3

func (sv *SVG) NodeEnsureUniqueId(kn ki.Ki)

NodeEnsureUniqueId ensures that the given node has a unique Id Call this on any newly-created nodes.

func (*SVG) OpenXML

func (sv *SVG) OpenXML(fname gi.FileName) error

OpenXML Opens XML-formatted SVG input from given file

func (*SVG) Paint

func (sv *SVG) Paint() *gist.Paint

Paint satisfies the painter interface

func (*SVG) ReadXML

func (sv *SVG) ReadXML(reader io.Reader) error

ReadXML reads XML-formatted SVG input from io.Reader, and uses xml.Decoder to create the SVG scenegraph for corresponding SVG drawing. Removes any existing content in SVG first. To process a byte slice, pass: bytes.NewReader([]byte(str)) -- all errors are logged and also returned. If this is being read into a live scenegraph, then you MUST call

svg.FullInit2DTree() after to initialize it for rendering.

func (*SVG) RemoveOrphanedDefs added in v1.2.3

func (sv *SVG) RemoveOrphanedDefs() bool

RemoveOrphanedDefs removes any items from Defs that are not actually referred to by anything in the current SVG tree. Returns true if items were removed. Does not remove gradients with StopsName = "" with extant stops -- these should be removed manually, as they are not automatically generated.

func (*SVG) Render2D

func (sv *SVG) Render2D()

func (*SVG) SaveXML added in v1.2.0

func (sv *SVG) SaveXML(fname gi.FileName) error

SaveXML saves the svg to a XML-encoded file, using WriteXML

func (*SVG) SetDPIXForm

func (sv *SVG) SetDPIXForm()

SetDPIXForm sets a scaling transform to compensate for the dpi -- svg rendering is done within a 96 DPI context

func (*SVG) SetNormXForm

func (sv *SVG) SetNormXForm()

SetNormXForm sets a scaling transform to make the entire viewbox to fit the viewport

func (*SVG) Size2D

func (sv *SVG) Size2D(iter int)

func (*SVG) Style2D

func (sv *SVG) Style2D()

func (*SVG) StyleSVG

func (sv *SVG) StyleSVG()

func (*SVG) UnmarshalXML

func (sv *SVG) UnmarshalXML(decoder *xml.Decoder, se xml.StartElement) error

UnmarshalXML unmarshals the svg using xml.Decoder

func (*SVG) UpdateAllGradientStops added in v1.2.17

func (sv *SVG) UpdateAllGradientStops()

UpdateAllGradientStops removes any items from Defs that are not actually referred to by anything in the current SVG tree. Returns true if items were removed. Does not remove gradients with StopsName = "" with extant stops -- these should be removed manually, as they are not automatically generated.

func (*SVG) WriteXML added in v1.2.0

func (sv *SVG) WriteXML(wr io.Writer, indent bool) error

WriteXML writes XML-formatted SVG output to io.Writer, and uses XMLEncoder

type SVGFlags added in v1.2.2

type SVGFlags int

SVGFlags extend gi.VpFlags to hold SVG node state

const (
	// Rendering means that the SVG is currently redrawing
	// Can be useful to check for animations etc to decide whether to
	// drive another update
	Rendering SVGFlags = SVGFlags(gi.VpFlagsN) + iota

	SVGFlagsN
)

func StringToSVGFlags added in v1.2.2

func StringToSVGFlags(s string) (SVGFlags, error)

func (SVGFlags) String added in v1.2.2

func (i SVGFlags) String() string

type Text

type Text struct {
	NodeBase
	Pos          mat32.Vec2 `xml:"{x,y}" desc:"position of the left, baseline of the text"`
	Width        float32    `xml:"width" desc:"width of text to render if using word-wrapping"`
	Text         string     `xml:"text" desc:"text string to render"`
	TextRender   girl.Text  `xml:"-" json:"-" desc:"render version of text"`
	CharPosX     []float32  `desc:"character positions along X axis, if specified"`
	CharPosY     []float32  `desc:"character positions along Y axis, if specified"`
	CharPosDX    []float32  `desc:"character delta-positions along X axis, if specified"`
	CharPosDY    []float32  `desc:"character delta-positions along Y axis, if specified"`
	CharRots     []float32  `desc:"character rotations, if specified"`
	TextLength   float32    `desc:"author's computed text length, if specified -- we attempt to match"`
	AdjustGlyphs bool       `desc:"in attempting to match TextLength, should we adjust glyphs in addition to spacing?"`
	LastPos      mat32.Vec2 `xml:"-" json:"-" desc:"last text render position -- lower-left baseline of start"`
	LastBBox     mat32.Box2 `xml:"-" json:"-" desc:"last actual bounding box in display units (dots)"`
}

Text renders SVG text, handling both text and tspan elements. tspan is nested under a parent text -- text has empty Text string.

func AddNewText added in v0.9.7

func AddNewText(parent ki.Ki, name string, x, y float32, text string) *Text

AddNewText adds a new text to given parent node, with given name, pos and text.

func (*Text) ApplyDeltaXForm added in v1.2.0

func (g *Text) ApplyDeltaXForm(trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2)

ApplyDeltaXForm applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Text) ApplyXForm added in v1.2.0

func (g *Text) ApplyXForm(xf mat32.Mat2)

ApplyXForm applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Text) BBox2D

func (g *Text) BBox2D() image.Rectangle

func (*Text) CopyFieldsFrom added in v0.9.8

func (g *Text) CopyFieldsFrom(frm interface{})

func (*Text) IsParText added in v1.2.5

func (g *Text) IsParText() bool

IsParText returns true if this element serves as a parent text element to tspan elements within it. This is true if NumChildren() > 0 and Text == ""

func (*Text) ReadGeom added in v1.2.0

func (g *Text) ReadGeom(dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Text) Render2D

func (g *Text) Render2D()

func (*Text) RenderText added in v1.2.0

func (g *Text) RenderText()

RenderText renders the text in full coords

func (*Text) SVGLocalBBox added in v1.2.5

func (g *Text) SVGLocalBBox() mat32.Box2

func (*Text) SVGName added in v1.2.0

func (g *Text) SVGName() string

func (*Text) SetPos added in v1.2.3

func (g *Text) SetPos(pos mat32.Vec2)

func (*Text) SetSize added in v1.2.3

func (g *Text) SetSize(sz mat32.Vec2)

func (*Text) TextBBox added in v1.2.5

func (g *Text) TextBBox() mat32.Box2

TextBBox returns the bounding box in local coordinates

func (*Text) WriteGeom added in v1.2.0

func (g *Text) WriteGeom(dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type ViewBox

type ViewBox struct {
	Min                 mat32.Vec2                 `desc:"offset or starting point in parent Viewport2D"`
	Size                mat32.Vec2                 `desc:"size of viewbox within parent Viewport2D"`
	PreserveAspectRatio ViewBoxPreserveAspectRatio `desc:"how to scale the view box within parent Viewport2D"`
}

ViewBox is used in SVG to define the coordinate system

func (*ViewBox) Defaults

func (vb *ViewBox) Defaults()

Defaults returns viewbox to defaults

type ViewBoxAlign

type ViewBoxAlign int32

ViewBoxAlign defines values for the PreserveAspectRatio alignment factor

const (
	NoAlign ViewBoxAlign = 1 << iota          // do not preserve uniform scaling
	XMin                                      // align ViewBox.Min with smallest values of Viewport
	XMid                                      // align ViewBox.Min with midpoint values of Viewport
	XMax                                      // align ViewBox.Min+Size with maximum values of Viewport
	XMask   ViewBoxAlign = XMin + XMid + XMax // mask for X values -- clear all X before setting new one
	YMin    ViewBoxAlign = 1 << iota          // align ViewBox.Min with smallest values of Viewport
	YMid                                      // align ViewBox.Min with midpoint values of Viewport
	YMax                                      // align ViewBox.Min+Size with maximum values of Viewport
	YMask   ViewBoxAlign = YMin + YMid + YMax // mask for Y values -- clear all Y before setting new one
)

type ViewBoxMeetOrSlice

type ViewBoxMeetOrSlice int32

ViewBoxMeetOrSlice defines values for the PreserveAspectRatio meet or slice factor

const (
	// Meet means the entire ViewBox is visible within Viewport, and it is
	// scaled up as much as possible to meet the align constraints
	Meet ViewBoxMeetOrSlice = iota

	// Slice means the entire ViewBox is covered by the ViewBox, and the
	// ViewBox is scaled down as much as possible, while still meeting the
	// align constraints
	Slice

	ViewBoxMeetOrSliceN
)

func (*ViewBoxMeetOrSlice) FromString

func (i *ViewBoxMeetOrSlice) FromString(s string) error

func (ViewBoxMeetOrSlice) MarshalJSON added in v0.9.10

func (ev ViewBoxMeetOrSlice) MarshalJSON() ([]byte, error)

func (ViewBoxMeetOrSlice) String

func (i ViewBoxMeetOrSlice) String() string

func (*ViewBoxMeetOrSlice) UnmarshalJSON added in v0.9.10

func (ev *ViewBoxMeetOrSlice) UnmarshalJSON(b []byte) error

type ViewBoxPreserveAspectRatio

type ViewBoxPreserveAspectRatio struct {
	Align       ViewBoxAlign       `svg:"align" desc:"how to align x,y coordinates within viewbox"`
	MeetOrSlice ViewBoxMeetOrSlice `svg:"meetOrSlice" desc:"how to scale the view box relative to the viewport"`
}

ViewBoxPreserveAspectRatio determines how to scale the view box within parent Viewport2D

type XMLEncoder added in v1.2.0

type XMLEncoder struct {
	Writer      io.Writer
	DoIndent    bool
	IndBytes    []byte
	PreBytes    []byte
	CurIndent   int
	CurStart    string
	NoEndIndent bool
}

XMLEncoder is a minimal XML encoder that formats output with Attr each on a new line, using same API as xml.Encoder

func NewXMLEncoder added in v1.2.0

func NewXMLEncoder(wr io.Writer) *XMLEncoder

func (*XMLEncoder) EncodeToken added in v1.2.0

func (xe *XMLEncoder) EncodeToken(t xml.Token) error

func (*XMLEncoder) EscapeString added in v1.2.0

func (xe *XMLEncoder) EscapeString(s string, escapeNewline bool)

EscapeString writes to p the properly escaped XML equivalent of the plain text data s.

func (*XMLEncoder) Flush added in v1.2.0

func (xe *XMLEncoder) Flush()

func (*XMLEncoder) Indent added in v1.2.0

func (xe *XMLEncoder) Indent(prefix, indent string)

func (*XMLEncoder) WriteEOL added in v1.2.0

func (xe *XMLEncoder) WriteEOL()

func (*XMLEncoder) WriteEnd added in v1.2.0

func (xe *XMLEncoder) WriteEnd(name string) error

func (*XMLEncoder) WriteIndent added in v1.2.0

func (xe *XMLEncoder) WriteIndent()

func (*XMLEncoder) WriteStart added in v1.2.0

func (xe *XMLEncoder) WriteStart(start *xml.StartElement) error

func (*XMLEncoder) WriteString added in v1.2.0

func (xe *XMLEncoder) WriteString(str string)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL