geom

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package geom 是与具体绘制库无关的二维几何与渐变引擎,供 internal/render 及其各绘制后端(canvas/gg/ftgg/tinyskia)共用。

说明:本包的路径子系统(path.go、path_intersection.go、path_stroke.go、 path_util.go、path_simplify.go、path_tiling.go、path_scanner.go、shapes.go、 polyline.go、util.go)是从 MIT 许可的 github.com/tdewolff/canvas 路径引擎 移植而来,以保证布尔运算(And/Or)、描边展开(Stroke)、Settle 等结果与 canvas 逐点一致。为便于与上游对照,这些文件保留了上游英文注释;本仓库 新增或修改的代码(colors.go、paint.go 等)使用中文注释。

移植时只删除了依赖渲染分辨率(Resolution)的 ToVectorRasterizer / ToScanxScanner,以及两处紧跟 panic 的不可达 continue 和已废弃 FastClip 的旧实现,其余逻辑未改动。

Index

Constants

View Source
const (
	MoveToCmd = 1.0
	LineToCmd = 2.0
	QuadToCmd = 4.0
	CubeToCmd = 8.0
	ArcToCmd  = 16.0
	CloseCmd  = 32.0
)

Command values as powers of 2 so that the float64 representation is exact TODO: make CloseCmd a LineTo + CloseCmd, where CloseCmd is only a command value, no coordinates TODO: optimize command memory layout in paths: we need three bits to represent each command, thus 6 to specify command going forward and going backward. The remaining 58 bits, or 28 per direction, should specify the index into Path.d of the end of the sequence of coordinates. MoveTo should have an index to the end of the subpath. Use math.Float64bits. For long flat paths this will reduce memory usage in half since besides all coordinates, the only overhead is: 64 bits first MoveTo, 64 bits end of MoveTo and start of LineTo, 64 bits end of LineTo and start of Close, 64 bits end of Close.

View Source
const DefaultResolution = Resolution(96.0 / mmPerInch)

DefaultResolution 是默认分辨率,等于 96 DPI。

Variables

View Source
var (
	Transparent = color.RGBA{0x00, 0x00, 0x00, 0x00}
	Black       = color.RGBA{0x00, 0x00, 0x00, 0xff}
	White       = color.RGBA{0xff, 0xff, 0xff, 0xff}
)

常用颜色(与 canvas 的 Transparent/Black/White 一致)。

View Source
var BentleyOttmannEpsilon = 1e-8

BentleyOttmannEpsilon is the snap rounding grid used by the Bentley-Ottmann algorithm. This prevents numerical issues. It must be larger than Epsilon since we use that to calculate intersections between segments. It is the number of binary digits to keep.

View Source
var DebugPathIntersection = false

DebugPathIntersection enables debugging mode for path intersection edge-cases. Please send us the test cases generated as temporary files.

View Source
var Epsilon = 1e-10

Epsilon is the smallest number below which we assume the value to be zero. This is to avoid numerical floating point issues.

View Source
var FastStroke = false

FastStroke skips "settling" the resulting paths for Path.Offset and Path.Stroke, which ensures a well-formed path without overlapping nor holes. This fixes overlapping strokes or the inner-bend for corners. Inner-bends are currently already fixed for two line segments, but will otherwise leave a hole. Overlapping strokes may not be a problem when using the NonZero winding order for drawing. Strokes that are significantly larger than the path itself may be problematic with this enabled, but it may provide a stark performance gain for most (trivial) cases.

View Source
var Identity = Matrix{
	{1.0, 0.0, 0.0},
	{0.0, 1.0, 0.0},
}

Identity is the identity affine transformation matrix, i.e. transforms any point to itself.

View Source
var Origin = Point{0.0, 0.0}

Origin is the coordinate system's origin.

View Source
var PixelTolerance = 0.1

PixelTolerance is the maximum deviation of the rasterized path from the original for flattening purposed in pixels.

View Source
var Precision = 8

Precision is the number of significant digits at which floating point value will be printed to output formats.

View Source
var Tolerance = 0.01

Tolerance is the maximum deviation from the original path in millimeters when e.g. flatting. Used for flattening in the renderers, font decorations, and path intersections.

Functions

func Equal

func Equal(a, b float64) bool

Equal returns true if a and b are equal within an absolute tolerance of Epsilon or within a relative tolerance of Epsilon (relative to the largest of the two).

func Interval

func Interval(f, lower, upper float64) bool

Interval returns true if f is in closed interval [lower-Epsilon,upper+Epsilon] where lower and upper can be interchanged.

func IntervalExclusive

func IntervalExclusive(f, lower, upper float64) bool

IntervalExclusive returns true if f is in open interval [lower+Epsilon,upper-Epsilon] where lower and upper can be interchanged.

func SolveCubicFormula

func SolveCubicFormula(a, b, c, d float64) (float64, float64, float64)

func SolveQuadraticFormula

func SolveQuadraticFormula(a, b, c float64) (float64, float64)

Types

type ArcsJoiner

type ArcsJoiner struct {
	GapJoiner Joiner
	Limit     float64
}

ArcsJoiner is an arcs joiner.

func (ArcsJoiner) Join

func (j ArcsJoiner) Join(rhs, lhs *Path, halfWidth float64, pivot, n0, n1 Point, r0, r1 float64)

Join adds a join to a right-hand-side and left-hand-side path, of width 2*halfWidth, around a pivot point with starting and ending normals of n0 and n1, and radius of curvatures of the previous and next segments, which are positive for CCW arcs.

func (ArcsJoiner) String

func (j ArcsJoiner) String() string

type BevelJoiner

type BevelJoiner struct{}

BevelJoiner is a bevel joiner.

func (BevelJoiner) Join

func (BevelJoiner) Join(rhs, lhs *Path, halfWidth float64, pivot, n0, n1 Point, r0, r1 float64)

Join adds a join to a right-hand-side and left-hand-side path, of width 2*halfWidth, around a pivot point with starting and ending normals of n0 and n1, and radius of curvatures of the previous and next segments.

func (BevelJoiner) String

func (BevelJoiner) String() string

type ButtCapper

type ButtCapper struct{}

ButtCapper is a butt capper.

func (ButtCapper) Cap

func (ButtCapper) Cap(p *Path, halfWidth float64, pivot, n0 Point)

Cap adds a cap to path p of width 2*halfWidth, at a pivot point and initial normal direction of n0.

func (ButtCapper) String

func (ButtCapper) String() string

type CSSColor

type CSSColor color.RGBA

CSSColor is a string formatter to convert a color.RGBA to a CSS color (hexadecimal or using rgba()).

func (CSSColor) String

func (color CSSColor) String() string

type Capper

type Capper interface {
	Cap(*Path, float64, Point, Point)
}

Capper implements Cap, with rhs the path to append to, halfWidth the half width of the stroke, pivot the pivot point around which to construct a cap, and n0 the normal at the start of the path. The length of n0 is equal to the halfWidth.

var ButtCap Capper = ButtCapper{}

ButtCap caps the start or end of a path by a butt cap.

var RoundCap Capper = RoundCapper{}

RoundCap caps the start or end of a path by a round cap.

var SquareCap Capper = SquareCapper{}

SquareCap caps the start or end of a path by a square cap.

type CoordinateFilter

type CoordinateFilter func(Point) bool

type FillRule

type FillRule int

FillRule is the algorithm to specify which area is to be filled and which not, in particular when multiple subpaths overlap. The NonZero rule is the default and will fill any point that is being enclosed by an unequal number of paths winding clock-wise and counter clock-wise, otherwise it will not be filled. The EvenOdd rule will fill any point that is being enclosed by an uneven number of paths, whichever their direction. Positive fills only counter clock-wise oriented paths, while Negative fills only clock-wise oriented paths.

const (
	NonZero FillRule = iota
	EvenOdd
	Positive
	Negative
)

see FillRule

func (FillRule) Fills

func (fillRule FillRule) Fills(windings int) bool

func (FillRule) String

func (fillRule FillRule) String() string

type Grad

type Grad []Stop

Grad 是按 offset 升序排列的渐变色标集合。

func NewGradient

func NewGradient() Grad

NewGradient 返回空的渐变色标集合。

func (*Grad) Add

func (g *Grad) Add(t float64, c color.RGBA)

Add 插入或替换一个色标,保持升序。

func (Grad) At

func (g Grad) At(t float64) color.RGBA

At 返回位置 t ∈ [0,1] 处的颜色(线性插值,端点外取端点色)。

func (Grad) ToLinear

func (g Grad) ToLinear(start, end Point) *LinearGradient

ToLinear 把色标集合绑定到线性渐变。

func (Grad) ToRadial

func (g Grad) ToRadial(c0 Point, r0 float64, c1 Point, r1 float64) *RadialGradient

ToRadial 把色标集合绑定到径向渐变。

type Gradient

type Gradient interface {
	At(x, y float64) color.RGBA
}

Gradient 是与具体绘制库无关的渐变采样接口:返回 (x,y) 处的颜色。 canvas 后端把它包装成 canvas.Gradient;gg 等后端直接用采样画笔消费。

type GradientFunc

type GradientFunc func(x, y float64) color.RGBA

GradientFunc 让普通函数实现 Gradient。

func (GradientFunc) At

func (f GradientFunc) At(x, y float64) color.RGBA

At 实现 Gradient。

type Intersection

type Intersection struct {
	Point              // coordinate of intersection
	T       [2]float64 // position along segment [0,1]
	Dir     [2]float64 // direction at intersection [0,2*pi)
	Tangent bool       // intersection is tangent (touches) instead of secant (crosses)
	Same    bool       // intersection is of two overlapping segments (tangent is also true)
}

Intersection is an intersection between two path segments, e.g. Line x Line. Note that an intersection is tangent also when it is at one of the endpoints, in which case it may be tangent for this segment but may or may not cross the path depending on the adjacent segment. Notabene: for quad/cube/ellipse aligned angles at the endpoint for non-overlapping curves are deviated slightly to correctly calculate the value for Into, and will thus not be aligned

func (Intersection) Equals

func (z Intersection) Equals(o Intersection) bool

func (Intersection) Into

func (z Intersection) Into() bool

Into returns true if first path goes into the left-hand side of the second path, i.e. the second path goes to the right-hand side of the first path.

func (Intersection) String

func (z Intersection) String() string

type Intersections

type Intersections []Intersection

func (Intersections) Has

func (zs Intersections) Has() bool

Has returns true if there are secant/tangent intersections.

func (Intersections) HasSecant

func (zs Intersections) HasSecant() bool

HasSecant returns true when there are secant intersections, i.e. the curves intersect and cross (they cut).

func (Intersections) HasTangent

func (zs Intersections) HasTangent() bool

HasTangent returns true when there are tangent intersections, i.e. the curves intersect but don't cross (they touch).

type Joiner

type Joiner interface {
	Join(*Path, *Path, float64, Point, Point, Point, float64, float64)
}

Joiner implements Join, with rhs the right path and lhs the left path to append to, pivot the intersection of both path elements, n0 and n1 the normals at the start and end of the path respectively. The length of n0 and n1 are equal to the halfWidth.

var ArcsClipJoin Joiner = ArcsJoiner{nil, 4.0}
var ArcsJoin Joiner = ArcsJoiner{BevelJoin, 4.0}

ArcsJoin connects two path elements by extending the ends of the paths as circle arcs until they meet. If this point is further than the limit, this will result in a bevel join (ArcsJoin) or they will meet at the limit (ArcsClipJoin).

var BevelJoin Joiner = BevelJoiner{}

BevelJoin connects two path elements by a linear join.

var MiterClipJoin Joiner = MiterJoiner{nil, 4.0} // TODO: should extend limit*halfwidth before bevel
var MiterJoin Joiner = MiterJoiner{BevelJoin, 4.0}

MiterJoin connects two path elements by extending the ends of the paths as lines until they meet. If this point is further than the limit, this will result in a bevel join (MiterJoin) or they will meet at the limit (MiterClipJoin).

var RoundJoin Joiner = RoundJoiner{}

RoundJoin connects two path elements by a round join.

type LinearGradient

type LinearGradient struct {
	Grad
	Start, End Point
	// contains filtered or unexported fields
}

LinearGradient 是 start→end 的线性渐变。

func NewLinearGradient

func NewLinearGradient(start, end Point) *LinearGradient

NewLinearGradient 返回线性渐变。

func (*LinearGradient) At

func (g *LinearGradient) At(x, y float64) color.RGBA

At 返回 (x,y) 处的颜色。

type Matrix

type Matrix [2][3]float64

Matrix is used for affine transformations, which are transformations such as translation, scaling, reflection, rotation, shear stretching. See https://en.wikipedia.org/wiki/Affine_transformation#Image_transformation for an overview of the transformations. The affine transformation matrix contains all transformations in a matrix, where we can concatenate transformations to apply them sequentially. Be aware that concatenated transformations will be evaluated right-to-left! So that Identity.Rotate(30).Translate(20,0) will first translate 20 points horizontally and then rotate 30 degrees counter clockwise.

func ParallelogramCell

func ParallelogramCell(a, b, rot float64) Matrix

ParallelogramCell is a paralellogram cell with sides of length a and b at an angle of rot degrees used for tiling.

func PrimitiveCell

func PrimitiveCell(a, b Point) Matrix

PrimitiveCell is a (primitive) cell used for tiling.

func RectangleCell

func RectangleCell(a, b float64) Matrix

RectangleCell is a rectangular cell with width a and height b used for tiling.

func RhombusCell

func RhombusCell(a float64) Matrix

RhombusCell is a rhombus cell with sides of length a at an angle of 120 degrees used for tiling.

func SquareCell

func SquareCell(a float64) Matrix

SquareCell is a square cell with sides of length a used for tiling.

func TileRectangle

func TileRectangle(cell Matrix, dst, src Rect) []Matrix

TileRectangle tiles the given cell (determines the axes along which cells are repeated) onto the rectangle dst (bounds of clipping path), where cells are filled by rectangle src (bounds of object to be tiled).

func (Matrix) Decompose

func (m Matrix) Decompose() (float64, float64, float64, float64, float64, float64)

Decompose extracts the translation, rotation, scaling and rotation components (applied in the reverse order) as (tx, ty, theta, sx, sy, phi) with rotation counter clockwise. This corresponds to Identity.Translate(tx, ty).Rotate(phi).Scale(sx, sy).Rotate(theta).

func (Matrix) Det

func (m Matrix) Det() float64

Det returns the matrix determinant.

func (Matrix) Dot

func (m Matrix) Dot(p Point) Point

Dot returns the dot product between the matrix and the given vector, i.e. applying the transformation.

func (Matrix) Eigen

func (m Matrix) Eigen() (float64, float64, Point, Point)

Eigen returns the matrix eigenvalues and eigenvectors. The first eigenvalue is related to the first eigenvector, and so for the second pair. Eigenvectors are normalized.

func (Matrix) Equals

func (m Matrix) Equals(q Matrix) bool

Equals returns true if both matrices are equal with a tolerance of Epsilon.

func (Matrix) HasRotation

func (m Matrix) HasRotation() bool

HasRotation is true if the matrix has a rotation or skewing component.

func (Matrix) HasScaling

func (m Matrix) HasScaling() bool

HasScaling is true if the matrix contains a scaling component.

func (Matrix) HasTranslation

func (m Matrix) HasTranslation() bool

HasTranslation is true if the matrix contains a translational component.

func (Matrix) Inv

func (m Matrix) Inv() Matrix

Inv returns the matrix inverse.

func (Matrix) IsIdentity

func (m Matrix) IsIdentity() bool

func (Matrix) IsRigid

func (m Matrix) IsRigid() bool

IsRigid is true if the matrix is orthogonal and consists of only isometric transformations: translation, rotation, and reflection.

func (Matrix) IsRotation

func (m Matrix) IsRotation() bool

IsRotation is true if the matrix consists of only rotational components, i.e. no scaling or skew transformations (but may translate).

func (Matrix) IsScaling

func (m Matrix) IsScaling() bool

IsScaling is true if the matrix consists of only scaling components, i.e. no rotation, or skew transformations (but may translate).

func (Matrix) IsSimilarity

func (m Matrix) IsSimilarity() bool

IsSimilarity is true if the matrix consists of only translation, rotation, reflection, and uniform scaling transformations. Uniform scaling means that it scales equally horizontally as vertically. If the scaling factor is 1.0, it is also a rigid transformation.

func (Matrix) IsTranslation

func (m Matrix) IsTranslation() bool

IsTranslation is true if the matrix consists of only translational components, i.e. no rotation, scaling, or skew transformations.

func (Matrix) Mul

func (m Matrix) Mul(q Matrix) Matrix

Mul multiplies the current matrix by the given matrix, i.e. combining transformations.

func (Matrix) Pos

func (m Matrix) Pos() (float64, float64)

Pos extracts the translation component as (tx,ty).

func (Matrix) ReflectX

func (m Matrix) ReflectX() Matrix

ReflectX adds a horizontal reflection transformation, i.e. Scale(-1,1).

func (Matrix) ReflectXAbout

func (m Matrix) ReflectXAbout(x float64) Matrix

ReflectXAbout adds a horizontal reflection transformation about x.

func (Matrix) ReflectY

func (m Matrix) ReflectY() Matrix

ReflectY adds a vertical reflection transformation, i.e. Scale(1,-1).

func (Matrix) ReflectYAbout

func (m Matrix) ReflectYAbout(y float64) Matrix

ReflectYAbout adds a vertical reflection transformation about y.

func (Matrix) Rotate

func (m Matrix) Rotate(rot float64) Matrix

Rotate adds a rotation transformation with rot in degree counter clockwise.

func (Matrix) RotateAbout

func (m Matrix) RotateAbout(rot, x, y float64) Matrix

RotateAbout adds a rotation transformation about (x,y) with rot in degrees counter clockwise.

func (Matrix) Scale

func (m Matrix) Scale(sx, sy float64) Matrix

Scale adds a scaling transformation in sx and sy. When scale is negative it will flip those axes.

func (Matrix) ScaleAbout

func (m Matrix) ScaleAbout(sx, sy, x, y float64) Matrix

ScaleAbout adds a scaling transformation about (x,y) in sx and sy. When scale is negative it will flip those axes.

func (Matrix) Shear

func (m Matrix) Shear(sx, sy float64) Matrix

Shear adds a shear transformation with sx the horizontal shear and sy the vertical shear.

func (Matrix) ShearAbout

func (m Matrix) ShearAbout(sx, sy, x, y float64) Matrix

ShearAbout adds a shear transformation about (x,y) with sx the horizontal shear and sy the vertical shear.

func (Matrix) String

func (m Matrix) String() string

String returns a string representation of the affine transformation matrix as six values, where [a b c; d e f; g h i] will be written as "a b d e c f" as g, h and i have fixed values (0, 0 and 1 respectively).

func (Matrix) T

func (m Matrix) T() Matrix

T returns the matrix transpose.

func (Matrix) ToSVG

func (m Matrix) ToSVG(h float64) string

ToSVG writes out the matrix in SVG notation, taking care of the proper order of transformations.

func (Matrix) Translate

func (m Matrix) Translate(x, y float64) Matrix

Translate adds a translation in x and y.

type MiterJoiner

type MiterJoiner struct {
	GapJoiner Joiner
	Limit     float64
}

MiterJoiner is a miter joiner.

func (MiterJoiner) Join

func (j MiterJoiner) Join(rhs, lhs *Path, halfWidth float64, pivot, n0, n1 Point, r0, r1 float64)

Join adds a join to a right-hand-side and left-hand-side path, of width 2*halfWidth, around a pivot point with starting and ending normals of n0 and n1, and radius of curvatures of the previous and next segments.

func (MiterJoiner) String

func (j MiterJoiner) String() string

type Paint

type Paint struct {
	Color    color.Color
	Gradient Gradient
}

Paint 是填充/描边画笔:纯色或渐变,二者择一。

func GradientPaint

func GradientPaint(g Gradient) Paint

GradientPaint 返回渐变画笔。

func SolidPaint

func SolidPaint(c color.Color) Paint

SolidPaint 返回纯色画笔。

func (Paint) Has

func (p Paint) Has() bool

Has 判断画笔是否可绘制。

func (Paint) IsColor

func (p Paint) IsColor() bool

IsColor 判断画笔是否为纯色。

func (Paint) IsGradient

func (p Paint) IsGradient() bool

IsGradient 判断画笔是否为渐变。

type Path

type Path struct {
	// contains filtered or unexported fields
}

Path defines a vector path in 2D using a series of commands (MoveTo, LineTo, QuadTo, CubeTo, ArcTo and Close). Each command consists of a number of float64 values (depending on the command) that fully define the action. The first value is the command itself (as a float64). The last two values is the end point position of the pen after the action (x,y). QuadTo defined one control point (x,y) in between, CubeTo defines two control points, and ArcTo defines (rx,ry,phi,large+sweep) i.e. the radius in x and y, its rotation (in radians) and the large and sweep booleans in one float64. Only valid commands are appended, so that LineTo has a non-zero length, QuadTo's and CubeTo's control point(s) don't (both) overlap with the start and end point, and ArcTo has non-zero radii and has non-zero length. For ArcTo we also make sure the angle is in the range [0, 2*PI) and we scale the radii up if they appear too small to fit the arc.

func Arc

func Arc(r, theta0, theta1 float64) *Path

Arc returns a circular arc with radius r and theta0 and theta1 the angles in degrees of the ellipse (before rot is applies) between which the arc will run. If theta0 < theta1, the arc will run in a CCW direction. If the difference between theta0 and theta1 is bigger than 360 degrees, one full circle will be drawn and the remaining part of diff % 360, e.g. a difference of 810 degrees will draw one full circle and an arc over 90 degrees.

func BeveledRectangle

func BeveledRectangle(w, h, r float64) *Path

BeveledRectangle returns a rectangle of width w and height h with beveled corners at distance r from the corner.

func Circle

func Circle(r float64) *Path

Circle returns a circle of radius r.

func Ellipse

func Ellipse(rx, ry float64) *Path

Ellipse returns an ellipse of radii rx and ry.

func EllipticalArc

func EllipticalArc(rx, ry, rot, theta0, theta1 float64) *Path

EllipticalArc returns an elliptical arc with radii rx and ry, with rot the counter clockwise rotation in degrees, and theta0 and theta1 the angles in degrees of the ellipse (before rot is applies) between which the arc will run. If theta0 < theta1, the arc will run in a CCW direction. If the difference between theta0 and theta1 is bigger than 360 degrees, one full circle will be drawn and the remaining part of diff % 360, e.g. a difference of 810 degrees will draw one full circle and an arc over 90 degrees.

func Grid

func Grid(w, h float64, nx, ny int, r float64) *Path

Grid returns a stroked grid of width w and height h, with grid line thickness r, and the number of cells horizontally and vertically as nx and ny respectively.

func Line

func Line(x, y float64) *Path

Line returns a line segment of from (0,0) to (x,y).

func MustParseSVGPath

func MustParseSVGPath(s string) *Path

MustParseSVGPath parses an SVG path data string and panics if it fails.

func NewPathFromData

func NewPathFromData(d []float64) *Path

NewPathFromData returns a new path using the raw data.

func ParseSVGPath

func ParseSVGPath(s string) (*Path, error)

ParseSVGPath parses an SVG path data string.

func Rectangle

func Rectangle(w, h float64) *Path

Rectangle returns a rectangle of width w and height h.

func RegularPolygon

func RegularPolygon(n int, r float64, up bool) *Path

RegularPolygon returns a regular polygon with radius r. It uses n vertices/edges, so when n approaches infinity this will return a path that approximates a circle. n must be 3 or more. The up boolean defines whether the first point will point upwards or downwards.

func RegularStarPolygon

func RegularStarPolygon(n, d int, r float64, up bool) *Path

RegularStarPolygon returns a regular star polygon with radius r. It uses n vertices of density d. This will result in a self-intersection star in counter clockwise direction. If n/2 < d the star will be clockwise and if n and d are not coprime a regular polygon will be obtained, possible with multiple windings. n must be 3 or more and d 2 or more. The up boolean defines whether the first point will point upwards or downwards.

func RoundedRectangle

func RoundedRectangle(w, h, r float64) *Path

RoundedRectangle returns a rectangle of width w and height h with rounded corners of radius r. A negative radius will cast the corners inwards (i.e. concave).

func StarPolygon

func StarPolygon(n int, R, r float64, up bool) *Path

StarPolygon returns a star polygon of n points with alternating radius R and r. The up boolean defines whether the first point will be point upwards or downwards.

func Triangle

func Triangle(r float64) *Path

Triangle returns a triangle of radius r pointing upwards.

func (*Path) And

func (p *Path) And(q *Path) *Path

And returns the boolean path operation of path p AND q, i.e. the intersection of both. It removes all self-intersections and overlapping areas, orients all filling paths CCW and all holes CW, and tries to separate paths as much as possible. Paths are grouped by the filling/outer ring followed by the corresponding holes/inner rings; the outer rings are ordered from left-to-right and secondly from bottom-to-top. Note that path p is flattened unless q is already flat. Path q is implicitly closed. It runs in O((n + k) log n), with n the number of segments, and k the number of intersections.

func (*Path) Append

func (p *Path) Append(qs ...*Path) *Path

Append appends path q to p and returns the extended path p.

func (*Path) Arc

func (p *Path) Arc(rx, ry, rot, theta0, theta1 float64)

Arc adds an elliptical arc with radii rx and ry, with rot the counter clockwise rotation in degrees, and theta0 and theta1 the angles in degrees of the ellipse (before rot is applies) between which the arc will run. If theta0 < theta1, the arc will run in a CCW direction. If the difference between theta0 and theta1 is bigger than 360 degrees, one full circle will be drawn and the remaining part of diff % 360, e.g. a difference of 810 degrees will draw one full circle and an arc over 90 degrees.

func (*Path) ArcTo

func (p *Path) ArcTo(rx, ry, rot float64, large, sweep bool, x, y float64)

ArcTo adds an arc with radii rx and ry, with rot the counter clockwise rotation with respect to the coordinate system in degrees, large and sweep booleans (see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#Arcs), and (x,y) the end position of the pen. The start position of the pen was given by a previous command's end point.

func (*Path) Bounds

func (p *Path) Bounds() Rect

Bounds returns the exact bounding box rectangle of the path.

func (*Path) CCW

func (p *Path) CCW() bool

CCW returns true when the path is counter clockwise oriented at its right-most coordinate (bottom-most of all right-most coordinates). It is most useful when knowing that the path does not self-intersect as it will tell you if the entire path is CCW or not. It will only return the result for the first subpath. It will return true for an empty path or a straight line.

func (*Path) Clip

func (p *Path) Clip(x0, y0, x1, y1 float64) *Path

Clip clips the path against the given rectangle. This is O(n), which is faster than using Path.And(rect.ToPath()) and does not alter the path structurally beyond removing sections.

func (*Path) Close

func (p *Path) Close()

Close closes a (sub)path with a LineTo to the start of the path (the most recent MoveTo command). It also signals the path closes as opposed to being just a LineTo command, which can be significant for stroking purposes for example.

func (*Path) Closed

func (p *Path) Closed() bool

Closed returns true if the last subpath of p is a closed path.

func (*Path) Contains

func (p *Path) Contains(q *Path) bool

Contains returns true if the interior of p contains the interior of q. Equal shapes contain each other. If p contains q, then q is within p. This tests DE-9IM's Covers relation.

func (*Path) ContainsPoint

func (p *Path) ContainsPoint(x, y float64, fillRule FillRule) bool

Contains returns whether the point (x,y) is contained/filled by the path. This depends on the FillRule. It uses a ray from (x,y) toward (∞,y) and counts the number of intersections with the path. When the point is on the boundary it is considered to be on the path's exterior.

func (*Path) CoordDirections

func (p *Path) CoordDirections() []Point

CoordDirections returns the direction of the segment start/end points. It will return the average direction at the intersection of two end points, and for an open path it will simply return the direction of the start and end points of the path.

func (*Path) Coords

func (p *Path) Coords() []Point

Coords returns all the coordinates of the segment start/end points. It omits zero-length CloseCmds.

func (*Path) Copy

func (p *Path) Copy() *Path

Copy returns a copy of p.

func (*Path) CopyTo

func (p *Path) CopyTo(q *Path) *Path

CopyTo returns a copy of p, using the memory of path q.

func (*Path) CrossingsAt

func (p *Path) CrossingsAt(x, y float64) (int, bool)

Crossings returns the number of crossings with the path from the given point outwards, i.e. the number of times a ray from (x,y) towards (∞,y) intersects the path. Additionally, it returns whether the point is on a path's boundary (which does not count towards the number of crossings).

func (*Path) CubeTo

func (p *Path) CubeTo(cpx1, cpy1, cpx2, cpy2, x, y float64)

CubeTo adds a cubic Bézier path with control points (cpx1,cpy1) and (cpx2,cpy2) and end point (x,y).

func (*Path) Curvature

func (p *Path) Curvature(seg int, t float64) float64

Curvature returns the curvature of the path at the given segment and t in [0.0,1.0] along that path. It is zero for straight lines and for non-existing segments.

func (*Path) Dash

func (p *Path) Dash(offset float64, d ...float64) *Path

Dash returns a new path that consists of dashes. The elements in d specify the width of the dashes and gaps. It will alternate between dashes and gaps when picking widths. If d is an array of odd length, it is equivalent of passing d twice in sequence. The offset specifies the offset used into d (or negative offset into the path). Dash will be applied to each subpath independently.

func (*Path) Data

func (p *Path) Data() []float64

Data returns the raw path data.

func (*Path) Direction

func (p *Path) Direction(seg int, t float64) Point

Direction returns the direction of the path at the given segment and t in [0.0,1.0] along that path. The direction is a vector of unit length.

func (*Path) Div

func (p *Path) Div(q *Path) *Path

Div returns the boolean path operation of path p DIV q, i.e. p divided by q. It removes all self-intersections and overlapping areas, orients all filling paths CCW and all holes CW, and tries to separate paths as much as possible. Paths are grouped by the filling/outer ring followed by the corresponding holes/inner rings; the outer rings are ordered from left-to-right and secondly from bottom-to-top. Note that path p is flattened unless q is already flat. Path q is implicitly closed. It runs in O((n + k) log n), with n the number of segments, and k the number of intersections.

func (*Path) Empty

func (p *Path) Empty() bool

Empty returns true if p is an empty path or consists of only MoveTos and Closes.

func (*Path) Equals

func (p *Path) Equals(q *Path) bool

Equals returns true if p and q are equal within tolerance Epsilon.

func (*Path) FastBounds

func (p *Path) FastBounds() Rect

FastBounds returns the maximum bounding box rectangle of the path. It is quicker than Bounds.

func (*Path) FastClip

func (p *Path) FastClip(x0, y0, x1, y1 float64) *Path

FastClip removes all segments that are completely outside the given clipping rectangle. To ensure that the removal doesn't cause a segment to cross the rectangle from the outside, it keeps points that cross at least two lines to infinity along the rectangle's edges. It doesn't clip crossing segments at the boundary like Path.Clip. NOTE: this is twice as slow as Path.Clip!

func (*Path) Filling

func (p *Path) Filling(fillRule FillRule) []bool

Filling returns whether each subpath gets filled or not. Whether a path is filled depends on the FillRule and whether it negates another path. If a subpath is not closed, it is implicitly assumed to be closed.

func (*Path) Flatten

func (p *Path) Flatten(tolerance float64) *Path

Flatten flattens all Bézier and arc curves into linear segments and returns a new path. It uses tolerance as the maximum deviation.

func (*Path) GobDecode

func (p *Path) GobDecode(b []byte) error

GobDecode implements the gob interface.

func (*Path) GobEncode

func (p *Path) GobEncode() ([]byte, error)

GobEncode implements the gob interface.

func (*Path) Gridsnap

func (p *Path) Gridsnap(spacing float64) *Path

Gridsnap snaps all vertices to a grid with the given spacing. This will significantly reduce numerical issues e.g. for path boolean operations. This operation is in-place.

func (*Path) HasSubpaths

func (p *Path) HasSubpaths() bool

HasSubpaths returns true when path p has subpaths. TODO: naming right? A simple path would not self-intersect. Add IsXMonotone and IsFlat as well?

func (*Path) Intersections

func (p *Path) Intersections(q *Path) []Point

Intersections returns a list of points of all intersections of path p with q. The intersection can be tangent (touch) or secant (cross). If the two paths are partially coincident it will return an intersection at the start and end. Equal paths have no intersections. If q is nil it returns the intersections of p with itself. Intersections are sorted from left-to-right, and otherwise from bottom-to-top.

func (*Path) IsFlat

func (p *Path) IsFlat() bool

IsFlat returns true if the path consists of solely line segments, that is only MoveTo, LineTo and Close commands.

func (*Path) Join

func (p *Path) Join(q *Path) *Path

Join joins path q to p and returns the extended path p (or q if p is empty). It's like executing the commands in q to p in sequence, where if the first MoveTo of q doesn't coincide with p, or if p ends in Close, it will fallback to appending the paths.

func (*Path) Len

func (p *Path) Len() int

Len returns the number of segments.

func (*Path) Length

func (p *Path) Length() float64

Length returns the length of the path in millimeters. The length is approximated for cubic Béziers.

func (*Path) LineTo

func (p *Path) LineTo(x, y float64)

LineTo adds a linear path to (x,y).

func (*Path) Markers

func (p *Path) Markers(first, mid, last *Path, align bool) []*Path

Markers returns an array of start, mid and end marker paths along the path at the coordinates between commands. Align will align the markers with the path direction so that the markers orient towards the path's left.

func (*Path) MarshalBinary

func (p *Path) MarshalBinary() ([]byte, error)

func (*Path) MoveTo

func (p *Path) MoveTo(x, y float64)

MoveTo moves the path to (x,y) without connecting the path. It starts a new independent subpath. Multiple subpaths can be useful when negating parts of a previous path by overlapping it with a path in the opposite direction. The behaviour for overlapping paths depends on the FillRule.

func (*Path) Not

func (p *Path) Not(q *Path) *Path

Not returns the boolean path operation of path p NOT q, i.e. the difference of both. It removes all self-intersections and overlapping areas, orients all filling paths CCW and all holes CW, and tries to separate paths as much as possible. Paths are grouped by the filling/outer ring followed by the corresponding holes/inner rings; the outer rings are ordered from left-to-right and secondly from bottom-to-top. Note that path p is flattened unless q is already flat. Path q is implicitly closed. It runs in O((n + k) log n), with n the number of segments, and k the number of intersections.

func (*Path) Offset

func (p *Path) Offset(w float64, tolerance float64) *Path

Offset offsets the path by w and returns a new path. A positive w will offset the path to the right-hand side, that is, it expands CCW oriented contours and contracts CW oriented contours. If you don't know the orientation you can use `Path.CCW` to find out, but if there may be self-intersection you should use `Path.Settle` to remove them and orient all filling contours CCW. The tolerance is the maximum deviation from the actual offset when flattening Béziers and optimizing the path.

func (*Path) Or

func (p *Path) Or(q *Path) *Path

Or returns the boolean path operation of path p OR q, i.e. the union of both. It It removes all self-intersections and overlapping areas, orients all filling paths CCW and all holes CW, and tries to separate paths as much as possible. Paths are grouped by the filling/outer ring followed by the corresponding holes/inner rings; the outer rings are ordered from left-to-right and secondly from bottom-to-top. Note that path p is flattened unless q is already flat. Path q is implicitly closed. It runs in O((n + k) log n), with n the number of segments, and k the number of intersections.

func (*Path) Overlaps

func (p *Path) Overlaps(q *Path) bool

Overlaps returns true if the interiors of p and q have at least one point in common. Either they have a secant intersection, one path in contained in the other, or both paths are equal. This is different from DE-9IM's definition of Overlaps.

func (*Path) PointClosed

func (p *Path) PointClosed() bool

PointClosed returns true if the last subpath of p is a closed path and the close command is a point and not a line.

func (*Path) Pos

func (p *Path) Pos() Point

Pos returns the current position of the path, which is the end point of the last command.

func (*Path) QuadTo

func (p *Path) QuadTo(cpx, cpy, x, y float64)

QuadTo adds a quadratic Bézier path with control point (cpx,cpy) and end point (x,y).

func (*Path) RayIntersections

func (p *Path) RayIntersections(x, y float64) []Intersection

RayIntersections returns the intersections of a path with a ray starting at (x,y) to (∞,y). An intersection is tangent only when it is at (x,y), i.e. the start of the ray. The parameter T along the ray is zero at the start but NaN otherwise. Intersections are sorted along the ray. This function runs in O(n) with n the number of path segments.

func (*Path) Relate

func (p *Path) Relate(q *Path) (Relation, []Point)

Relate returns the spatial relation as defined by DE-9IM between the two paths as well as the intersections between both. It is faster if you need to check multiple spatial relations and/or retrieve the intersections.

func (*Path) ReplaceArcs

func (p *Path) ReplaceArcs() *Path

ReplaceArcs replaces ArcTo commands by CubeTo commands and returns a new path.

func (*Path) Reset

func (p *Path) Reset()

Reset clears the path but retains the same memory. This can be used in loops where you append and process paths every iteration, and avoid new memory allocations.

func (*Path) Reverse

func (p *Path) Reverse() *Path

Reverse returns a new path that is the same path as p but in the reverse direction.

func (*Path) ReverseScanner

func (p *Path) ReverseScanner() *PathReverseScanner

ReverseScanner returns a path scanner in reverse order.

func (*Path) Rotate

func (p *Path) Rotate(deg float64) *Path

Rotate rotates the path by deg degrees counter clockwise. It modifies the path in-place.

func (*Path) Same

func (p *Path) Same(q *Path) bool

Same returns true if p and q are equal shapes within tolerance Epsilon. Path q may start at an offset into path p or may be in the reverse direction.

func (*Path) Sane

func (p *Path) Sane() bool

Sane returns true if the path is sane, ie. it does not have NaN or infinity values.

func (*Path) Scale

func (p *Path) Scale(sx, sy float64) *Path

Scale scales the path by (sx,sy). It modifies the path in-place.

func (*Path) Scanner

func (p *Path) Scanner() *PathScanner

Scanner returns a path scanner.

func (*Path) Segments

func (p *Path) Segments() []Segment

Segments returns the path segments as a slice of segment structures.

func (*Path) Settle

func (p *Path) Settle(fillRule FillRule) *Path

Settle returns the "settled"/flattened path, a visually identical version of the original. It removes all self-intersections and overlapping areas, orients all filling paths CCW and all holes CW, and tries to separate paths as much as possible. Paths are grouped by the filling/outer ring followed by the corresponding holes/inner rings; the outer rings are ordered from left-to-right and secondly from bottom-to-top. Note that path p is flattened unless q is already flat. It runs in O((n + k) log n), with n the number of segments, and k the number of intersections.

func (*Path) SimplifyVisvalingamWhyatt

func (p *Path) SimplifyVisvalingamWhyatt(tolerance float64) *Path

func (*Path) Split

func (p *Path) Split() []*Path

Split splits the path into its independent subpaths. The path is split before each MoveTo command.

func (*Path) SplitAt

func (p *Path) SplitAt(ts ...float64) []*Path

SplitAt splits the path into separate paths at the specified intervals (given in millimeters) along the path.

func (*Path) StartPos

func (p *Path) StartPos() Point

StartPos returns the start point of the current subpath, i.e. it returns the position of the last MoveTo command.

func (*Path) String

func (p *Path) String() string

String returns a string that represents the path similar to the SVG path data format (but not necessarily valid SVG).

func (*Path) Stroke

func (p *Path) Stroke(w float64, cr Capper, jr Joiner, tolerance float64) *Path

Stroke converts a path into a stroke of width w and returns a new path. It uses cr to cap the start and end of the path, and jr to join all path elements. If the path closes itself, it will use a join between the start and end instead of capping them. The tolerance is the maximum deviation from the original path when flattening Béziers and optimizing the stroke.

func (*Path) Tile

func (p *Path) Tile(clip *Path, cell Matrix) *Path

Tile tiles a path within a clipping path using the given primitive cell.

func (*Path) ToPDF

func (p *Path) ToPDF() string

ToPDF returns a string that represents the path in the PDF data format.

func (*Path) ToPS

func (p *Path) ToPS() string

ToPS returns a string that represents the path in the PostScript data format.

func (*Path) ToSVG

func (p *Path) ToSVG() string

ToSVG returns a string that represents the path in the SVG path data format with minification.

func (*Path) Touches

func (p *Path) Touches(q *Path) bool

Touches returns true if path p and q are not disjoint, their boundaries/interiors intersect. This is different from DE-9IM's definition of Touches.

func (*Path) Transform

func (p *Path) Transform(m Matrix) *Path

Transform transforms the path by the given transformation matrix. It modifies the path in-place.

func (*Path) TransformFunc

func (p *Path) TransformFunc(f func(float64, float64) (float64, float64)) *Path

TransformFunc transforms the path by the given function: (x,y)=>(x,y). It modifies the path in-place.

func (*Path) Translate

func (p *Path) Translate(x, y float64) *Path

Translate translates the path by (x,y). It modifies the path in-place.

func (*Path) Triangulate

func (p *Path) Triangulate() ([][3]Point, [][5]Point)

Triangulate tessellates the path with triangles that fill the path. WIP

func (*Path) UnmarshalBinary

func (p *Path) UnmarshalBinary(b []byte) error

func (*Path) WindingsAt

func (p *Path) WindingsAt(x, y float64) (int, bool)

Windings returns the number of windings at the given point, i.e. the sum of windings for each time a ray from (x,y) towards (∞,y) intersects the path. Counter clock-wise intersections count as positive, while clock-wise intersections count as negative. Additionally, it returns whether the point is on a path's boundary (which counts as being on the exterior).

func (*Path) XMonotone

func (p *Path) XMonotone() *Path

XMonotone replaces all Bézier and arc segments to be x-monotone and returns a new path, that is each path segment is either increasing or decreasing with X while moving across the segment. This is always true for line segments.

func (*Path) Xor

func (p *Path) Xor(q *Path) *Path

Xor returns the boolean path operation of path p XOR q, i.e. the symmetric difference of both. It removes all self-intersections and overlapping areas, orients all filling paths CCW and all holes CW, and tries to separate paths as much as possible. Paths are grouped by the filling/outer ring followed by the corresponding holes/inner rings; the outer rings are ordered from left-to-right and secondly from bottom-to-top. Note that path p is flattened unless q is already flat. Path q is implicitly closed. It runs in O((n + k) log n), with n the number of segments, and k the number of intersections.

type PathReverseScanner

type PathReverseScanner struct {
	// contains filtered or unexported fields
}

PathReverseScanner scans the path in reverse order.

func (*PathReverseScanner) Arc

Arc returns the arguments for arcs (rx,ry,rot,large,sweep).

func (*PathReverseScanner) CP1

func (s *PathReverseScanner) CP1() Point

CP1 returns the first control point for quadratic and cubic Béziers.

func (*PathReverseScanner) CP2

func (s *PathReverseScanner) CP2() Point

CP2 returns the second control point for cubic Béziers.

func (*PathReverseScanner) Cmd

func (s *PathReverseScanner) Cmd() float64

Cmd returns the current path segment command.

func (*PathReverseScanner) End

func (s *PathReverseScanner) End() Point

End returns the current path segment end position.

func (*PathReverseScanner) Path

func (s *PathReverseScanner) Path() *Path

Path returns the current path segment.

func (*PathReverseScanner) Scan

func (s *PathReverseScanner) Scan() bool

Scan scans a new path segment and should be called before the other methods.

func (*PathReverseScanner) Start

func (s *PathReverseScanner) Start() Point

Start returns the current path segment start position.

func (*PathReverseScanner) Values

func (s *PathReverseScanner) Values() []float64

Values returns the current path segment values.

type PathScanner

type PathScanner struct {
	// contains filtered or unexported fields
}

PathScanner scans the path.

func (*PathScanner) Arc

func (s *PathScanner) Arc() (float64, float64, float64, bool, bool)

Arc returns the arguments for arcs (rx,ry,rot,large,sweep).

func (*PathScanner) CP1

func (s *PathScanner) CP1() Point

CP1 returns the first control point for quadratic and cubic Béziers.

func (*PathScanner) CP2

func (s *PathScanner) CP2() Point

CP2 returns the second control point for cubic Béziers.

func (*PathScanner) Cmd

func (s *PathScanner) Cmd() float64

Cmd returns the current path segment command.

func (*PathScanner) End

func (s *PathScanner) End() Point

End returns the current path segment end position.

func (*PathScanner) Path

func (s *PathScanner) Path() *Path

Path returns the current path segment.

func (*PathScanner) Scan

func (s *PathScanner) Scan() bool

Scan scans a new path segment and should be called before the other methods.

func (*PathScanner) Start

func (s *PathScanner) Start() Point

Start returns the current path segment start position.

func (*PathScanner) Values

func (s *PathScanner) Values() []float64

Values returns the current path segment values.

type Paths

type Paths []*Path

func (Paths) And

func (ps Paths) And(qs Paths) Paths

And is the same as Path.And, but faster if paths are already split. Each resulting path is a single filling path followed by its holes as subpaths.

func (Paths) Div

func (ps Paths) Div(qs Paths) Paths

Div is the same as Path.DivideBy, but faster if paths are already split. Each resulting path is a single filling path followed by its holes as subpaths.

func (Paths) Empty

func (ps Paths) Empty() bool

func (Paths) Merge

func (ps Paths) Merge() *Path

func (Paths) Not

func (ps Paths) Not(qs Paths) Paths

Not is the same as Path.Not, but faster if paths are already split. Each resulting path is a single filling path followed by its holes as subpaths.

func (Paths) Or

func (ps Paths) Or(qs Paths) Paths

Or is the same as Path.Or, but faster if paths are already split. Each resulting path is a single filling path followed by its holes as subpaths.

func (Paths) Settle

func (ps Paths) Settle(fillRule FillRule) Paths

Settle is the same as Path.Settle, but faster if paths are already split. Each resulting path is a single filling path followed by its holes as subpaths.

func (Paths) Xor

func (ps Paths) Xor(qs Paths) Paths

Xor is the same as Path.Xor, but faster if paths are already split. Each resulting path is a single filling path followed by its holes as subpaths.

type Point

type Point struct {
	X, Y float64
}

Point is a coordinate in 2D space. OP refers to the line that goes through the origin (0,0) and this point (x,y).

func EllipsePos

func EllipsePos(rx, ry, phi, cx, cy, theta float64) Point

EllipsePos returns the position on the ellipse at angle theta.

func PolarPoint

func PolarPoint(angle, radius float64) Point

PolarPoint returns a point from polar coordinates, with angle in radians CCW and radius the distance from (0,0).

func (Point) Add

func (p Point) Add(q Point) Point

Add adds Q to P.

func (Point) Angle

func (p Point) Angle() float64

Angle returns the angle in radians [0,2PI) between the x-axis and OP.

func (Point) AngleBetween

func (p Point) AngleBetween(q Point) float64

AngleBetween returns the angle in radians [-PI,PI] from OP to OQ.

func (Point) Div

func (p Point) Div(f float64) Point

Div divides x and y by f.

func (Point) Dot

func (p Point) Dot(q Point) float64

Dot returns the dot product between OP and OQ, i.e. zero if perpendicular and |OP|*|OQ| if aligned.

func (Point) Equals

func (p Point) Equals(q Point) bool

Equals returns true if P and Q are equal with tolerance Epsilon.

func (Point) Gridsnap

func (p Point) Gridsnap(spacing float64) Point

Gridsnap snaps point to a grid with the given spacing.

func (Point) Hadamard

func (p Point) Hadamard(q Point) Point

Hadamard returns the Hadamard product, or the element-wise product, of the point.

func (Point) Interpolate

func (p Point) Interpolate(q Point, t float64) Point

Interpolate returns a point on PQ that is linearly interpolated by t in [0,1], i.e. t=0 returns P and t=1 returns Q.

func (Point) InterpolateX

func (p Point) InterpolateX(q Point, x float64) Point

func (Point) InterpolateY

func (p Point) InterpolateY(q Point, y float64) Point

func (Point) IsZero

func (p Point) IsZero() bool

IsZero returns true if P is exactly zero.

func (Point) Length

func (p Point) Length() float64

Length returns the length of OP.

func (Point) Mul

func (p Point) Mul(f float64) Point

Mul multiplies x and y by f.

func (Point) Neg

func (p Point) Neg() Point

Neg negates x and y.

func (Point) Norm

func (p Point) Norm(length float64) Point

Norm normalises OP to be of given length.

func (Point) PerpDot

func (p Point) PerpDot(q Point) float64

PerpDot returns the perp dot product between OP and OQ, i.e. zero if aligned and |OP|*|OQ| if perpendicular. This is the cross product in two dimensions.

func (Point) Rot

func (p Point) Rot(phi float64, p0 Point) Point

Rot rotates the line OP by phi radians CCW.

func (Point) Rot90CCW

func (p Point) Rot90CCW() Point

Rot90CCW rotates the line OP by 90 degrees CCW.

func (Point) Rot90CW

func (p Point) Rot90CW() Point

Rot90CW rotates the line OP by 90 degrees CW.

func (Point) Slope

func (p Point) Slope() float64

Slope returns the slope between OP, i.e. y/x.

func (Point) String

func (p Point) String() string

String returns the string representation of a point, such as "(x,y)".

func (Point) Sub

func (p Point) Sub(q Point) Point

Sub subtracts Q from P.

func (Point) Transform

func (p Point) Transform(m Matrix) Point

Transform transforms the point by affine transformation matrix m.

type Polyline

type Polyline struct {
	// contains filtered or unexported fields
}

Polyline defines a list of points in 2D space that form a polyline. If the last coordinate equals the first coordinate, we assume the polyline to close itself.

func PolylineFromPath

func PolylineFromPath(p *Path) *Polyline

PolylineFromPath returns a polyline from the given path by approximating it by linear line segments, i.e. by flattening.

func PolylineFromPathCoords

func PolylineFromPathCoords(p *Path) *Polyline

PolylineFromPathCoords returns a polyline from the given path from each of the start/end coordinates of the segments, i.e. converting all non-linear segments to linear ones.

func (*Polyline) Add

func (p *Polyline) Add(x, y float64) *Polyline

Add adds a new point to the polyline.

func (*Polyline) Area

func (p *Polyline) Area() float64

Area returns the polygon's signed area.

func (*Polyline) Centroid

func (p *Polyline) Centroid() Point

Centroid returns the center point of the polygon.

func (*Polyline) Close

func (p *Polyline) Close() *Polyline

Close adds a new point equal to the first, closing the polyline.

func (*Polyline) Closed

func (p *Polyline) Closed() bool

Closed returns true if the last point coincides with the first.

func (*Polyline) Coords

func (p *Polyline) Coords() []Point

Coords returns the list of coordinates of the polyline.

func (*Polyline) Empty

func (p *Polyline) Empty() bool

Empty returns true if the polyline is empty.

func (*Polyline) FillCount

func (p *Polyline) FillCount(x, y float64) int

FillCount returns the number of times the test point is enclosed by the polyline. Counter clockwise enclosures are counted positively and clockwise enclosures negatively.

func (*Polyline) Interior

func (p *Polyline) Interior(x, y float64, fillRule FillRule) bool

Interior is true when the point (x,y) is in the interior of the path, i.e. gets filled. This depends on the FillRule.

func (*Polyline) Len

func (p *Polyline) Len() int

Len returns the number of segments.

func (*Polyline) Smoothen

func (p *Polyline) Smoothen() *Path

Smoothen returns a new path that smoothens out a path using cubic Béziers between all the path points. It makes sure that the curvature is smooth along the whole path. If the path is closed it will be smooth between start and end segments too.

func (*Polyline) ToPath

func (p *Polyline) ToPath() *Path

ToPath converts the polyline to a path. If the last coordinate equals the first one, we close the path.

type RadialGradient

type RadialGradient struct {
	Grad
	C0, C1 Point
	R0, R1 float64
	// contains filtered or unexported fields
}

RadialGradient 是两个圆之间的径向渐变。

func NewRadialGradient

func NewRadialGradient(c0 Point, r0 float64, c1 Point, r1 float64) *RadialGradient

NewRadialGradient 返回径向渐变。

func (*RadialGradient) At

func (g *RadialGradient) At(x, y float64) color.RGBA

At 返回 (x,y) 处的颜色(参考 pixman-radial-gradient 实现)。

type Rect

type Rect struct {
	X0, Y0, X1, Y1 float64
}

Rect is a rectangle in 2D defined by a position and its width and height.

func RectFromPoints

func RectFromPoints(ps ...Point) Rect

func RectFromSize

func RectFromSize(x, y, w, h float64) Rect

func (Rect) Add

func (r Rect) Add(q Rect) Rect

Add returns a rect that encompasses both the current rect and the given rect.

func (Rect) AddPoint

func (r Rect) AddPoint(p Point) Rect

AddPoint returns a rect that encompasses both the current rect and the given point.

func (Rect) And

func (r Rect) And(q Rect) Rect

And returns the rectangle that is the overlap of both.

func (Rect) Area

func (r Rect) Area() float64

Area returns the area of the rectangle.

func (Rect) Center

func (r Rect) Center() Point

Center returns the center point.

func (Rect) ClosestPoint

func (r Rect) ClosestPoint(p Point) Point

ClosestPoint returns a point in the rectangle closest to the given point.

func (Rect) Contains

func (r Rect) Contains(q Rect) bool

Contains returns true if r contains q.

func (Rect) ContainsLine

func (r Rect) ContainsLine(a, b Point) bool

func (Rect) ContainsPoint

func (r Rect) ContainsPoint(p Point) bool

ContainsPoint returns true if the rectangle contains or touches an edge.

func (Rect) DistanceToPoint

func (r Rect) DistanceToPoint(p Point) float64

DistanceToPoint returns the distance between the rectangle and a point.

func (Rect) Empty

func (r Rect) Empty() bool

func (Rect) Equals

func (r Rect) Equals(q Rect) bool

Equals returns true if rectangles are equal with tolerance Epsilon.

func (Rect) Expand

func (r Rect) Expand(d float64) Rect

Expand expands the rectangle.

func (Rect) H

func (r Rect) H() float64

H returns the height of the rectangle.

func (Rect) Overlaps

func (r Rect) Overlaps(q Rect) bool

Overlaps returns true if both rectangles overlap.

func (Rect) OverlapsLine

func (r Rect) OverlapsLine(a, b Point) bool

func (Rect) String

func (r Rect) String() string

String returns a string representation of r such as "(xmin,ymin)-(xmax,ymax)".

func (Rect) ToPath

func (r Rect) ToPath() *Path

ToPath converts the rectangle to a path.

func (Rect) Touches

func (r Rect) Touches(q Rect) bool

Touches returns true if both rectangles touch (or overlap).

func (Rect) TouchesLine

func (r Rect) TouchesLine(a, b Point) bool

func (Rect) TouchesPoint

func (r Rect) TouchesPoint(p Point) bool

TouchesPoint returns true if the rectangle touches a point (within +-Epsilon).

func (Rect) Transform

func (r Rect) Transform(m Matrix) Rect

Transform transforms the rectangle by affine transformation matrix m and returns the new bounds of that rectangle.

func (Rect) Translate

func (r Rect) Translate(x, y float64) Rect

Translate translates the rect.

func (Rect) W

func (r Rect) W() float64

W returns the width of the rectangle.

func (Rect) Zero

func (r Rect) Zero() bool

type Relation

type Relation byte

The DE-9IM naming scheme is used for spatial relationships and geometry intersection classification. Note: - Contains does not include the boundary: a point/line completely on the boundary of a polygon is not contained by the polygon. - Touches means both geometries touch but do not overlap nor are equal/contained/covered - Overlaps means that both geometries overlap but are not equal/contained/covered

func (Relation) Contains

func (rel Relation) Contains() bool

Contains returns true if at least one point of the second shape lies in the first, and no points of the second lie in the exterior of the first.

func (Relation) CoveredBy

func (rel Relation) CoveredBy() bool

CoveredBy is the same as Covers but with the shapes swapped.

func (Relation) Covers

func (rel Relation) Covers() bool

Covers returns true if at least one point of the second shape lies in the first, and no points of the second lie in the exterior of the first, including boundaries. It is similar to Contains but includes lines on the boundary of an area.

func (Relation) Disjoint

func (rel Relation) Disjoint() bool

Disjoint is the inverse of Intersects.

func (Relation) Equals

func (rel Relation) Equals() bool

Equals returns true if all interior points of one are interior of the other, and the same for exterior points.

func (Relation) Intersects

func (rel Relation) Intersects() bool

Intersects returns true if both shapes have at least one point in common, ie. they may touch/overlap/contain/equal.

func (Relation) Overlaps

func (rel Relation) Overlaps() bool

Overlaps returns true if both shapes have some but not all points in common. This is different from the DE-9IM specification since it does not consider the dimensionality of the shapes. The result is that equal shapes do not overlap, points never overlap, crossing lines overlap, and contained/covered shapes do not overlap.

func (Relation) String

func (rel Relation) String() string

func (Relation) Touches

func (rel Relation) Touches() bool

Touches returns true if the shapes have a point in common but their interiors do not intersect, ie. their boundaries meet/overlap.

func (Relation) Within

func (rel Relation) Within() bool

Within is the same as Contains but with the shapes swapped.

type Resolution

type Resolution float64

Resolution 是栅格化输出分辨率,内部以「点/毫米」存储(与 canvas.Resolution 语义一致)。DPI 用于对外表达「点/英寸」。

func DPI

func DPI(dpi float64) Resolution

DPI 以点/英寸构造分辨率。

func DPMM

func DPMM(dpmm float64) Resolution

DPMM 以点/毫米构造分辨率。

func (Resolution) DPI

func (r Resolution) DPI() float64

DPI 返回点/英寸。

func (Resolution) DPMM

func (r Resolution) DPMM() float64

DPMM 返回点/毫米。

type RoundCapper

type RoundCapper struct{}

RoundCapper is a round capper.

func (RoundCapper) Cap

func (RoundCapper) Cap(p *Path, halfWidth float64, pivot, n0 Point)

Cap adds a cap to path p of width 2*halfWidth, at a pivot point and initial normal direction of n0.

func (RoundCapper) String

func (RoundCapper) String() string

type RoundJoiner

type RoundJoiner struct{}

RoundJoiner is a round joiner.

func (RoundJoiner) Join

func (RoundJoiner) Join(rhs, lhs *Path, halfWidth float64, pivot, n0, n1 Point, r0, r1 float64)

Join adds a join to a right-hand-side and left-hand-side path, of width 2*halfWidth, around a pivot point with starting and ending normals of n0 and n1, and radius of curvatures of the previous and next segments.

func (RoundJoiner) String

func (RoundJoiner) String() string

type Segment

type Segment struct {
	Cmd        float64
	Start, End Point
	// contains filtered or unexported fields
}

Segment is a path command.

func (Segment) Arc

func (seg Segment) Arc() (float64, float64, float64, bool, bool)

Arc returns the arguments for arcs (rx,ry,rot,large,sweep).

func (Segment) CP1

func (seg Segment) CP1() Point

CP1 returns the first control point for quadratic and cubic Béziers.

func (Segment) CP2

func (seg Segment) CP2() Point

CP2 returns the second control point for cubic Béziers.

type SquareCapper

type SquareCapper struct{}

SquareCapper is a square capper.

func (SquareCapper) Cap

func (SquareCapper) Cap(p *Path, halfWidth float64, pivot, n0 Point)

Cap adds a cap to path p of width 2*halfWidth, at a pivot point and initial normal direction of n0.

func (SquareCapper) String

func (SquareCapper) String() string

type Stop

type Stop struct {
	Offset float64
	Color  color.RGBA
}

Stop 是渐变色标。

type SweepEvents

type SweepEvents []*SweepPoint

SweepEvents is a heap priority queue of sweep events.

func (*SweepEvents) AddPathEndpoints

func (q *SweepEvents) AddPathEndpoints(p *Path, seg int, clipping bool) int

AddPathEndpoints adds all line segments of p to the queue q. The first command is converted to a MoveToCmd and any CloseCmd that is not at the end is converted to a LineToCmd.

func (SweepEvents) Init

func (q SweepEvents) Init()

func (SweepEvents) Less

func (q SweepEvents) Less(i, j int) bool

func (*SweepEvents) Pop

func (q *SweepEvents) Pop() *SweepPoint

func (SweepEvents) Print

func (q SweepEvents) Print(w io.Writer)

func (*SweepEvents) Push

func (q *SweepEvents) Push(item *SweepPoint)

func (SweepEvents) String

func (q SweepEvents) String() string

func (SweepEvents) Swap

func (q SweepEvents) Swap(i, j int)

func (*SweepEvents) Top

func (q *SweepEvents) Top() *SweepPoint

type SweepNode

type SweepNode struct {
	*SweepPoint
	// contains filtered or unexported fields
}

func (*SweepNode) Next

func (n *SweepNode) Next() *SweepNode

func (*SweepNode) Prev

func (n *SweepNode) Prev() *SweepNode

func (*SweepNode) Print

func (n *SweepNode) Print(w io.Writer)

type SweepPoint

type SweepPoint struct {
	// initial data
	Point // position of this endpoint
	// contains filtered or unexported fields
}

SweepPoint is of size 88 bytes on 64-bit architectures

func (*SweepPoint) CompareH

func (a *SweepPoint) CompareH(b *SweepPoint) int

func (*SweepPoint) CompareV

func (a *SweepPoint) CompareV(b *SweepPoint) int

func (*SweepPoint) InResult

func (s *SweepPoint) InResult(op pathOp, fillRule FillRule) uint8

func (*SweepPoint) InterpolateY

func (s *SweepPoint) InterpolateY(x float64) float64

func (*SweepPoint) LessH

func (a *SweepPoint) LessH(b *SweepPoint) bool

func (*SweepPoint) Reverse

func (s *SweepPoint) Reverse()

func (*SweepPoint) SplitAt

func (s *SweepPoint) SplitAt(z Point) (*SweepPoint, *SweepPoint)

func (*SweepPoint) String

func (s *SweepPoint) String() string

func (*SweepPoint) ToleranceEdgeY

func (s *SweepPoint) ToleranceEdgeY(xLeft, xRight float64) (float64, float64)

ToleranceEdgeY returns the y-value of the SweepPoint at the tolerance edges given by xLeft and xRight, or at the endpoints of the SweepPoint, whichever comes first.

type SweepStatus

type SweepStatus struct {
	// contains filtered or unexported fields
}

TODO: test performance versus (2,4)-tree (current LEDA implementation), (2,16)-tree (as proposed by S. Naber/Näher in "Comparison of search-tree data structures in LEDA. Personal communication" apparently), RB-tree (likely a good candidate), and an AA-tree (simpler implementation may be faster). Perhaps an unbalanced (e.g. Treap) works well due to the high number of insertions/deletions. In any case, measure the amount of finds and inserts/deletes. If finds >> inserts probably AVL is better, if somewhat similar or inserts > finds then perhaps an RB tree (store color in sign bit of node's height).

func (*SweepStatus) FindPrevNext

func (s *SweepStatus) FindPrevNext(item *SweepPoint) (*SweepNode, *SweepNode)

func (*SweepStatus) InsertAfter

func (s *SweepStatus) InsertAfter(n *SweepNode, item *SweepPoint) *SweepNode

func (*SweepStatus) Remove

func (s *SweepStatus) Remove(n *SweepNode)

func (*SweepStatus) String

func (s *SweepStatus) String() string

type VisvalingamWhyatt

type VisvalingamWhyatt struct {
	// contains filtered or unexported fields
}

func NewVisvalingamWhyatt

func NewVisvalingamWhyatt(filter CoordinateFilter) *VisvalingamWhyatt

func (*VisvalingamWhyatt) Simplify

func (s *VisvalingamWhyatt) Simplify(ps []*Path, tolerance float64) *Path

Jump to

Keyboard shortcuts

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