pixel

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2018 License: MIT Imports: 6 Imported by: 0

README

Pixel Build Status GoDoc Go Report Card

A hand-crafted 2D game library in Go. Take a look into the features to see what it can do.

go get github.com/faiface/pixel

See requirements for the list of libraries necessary for compilation.

Tutorial

The Wiki of this repo contains an extensive tutorial covering several topics of Pixel. Here's the content of the tutorial parts so far:

Examples

The examples repository contains a few examples demonstrating Pixel's functionality.

To run an example, navigate to it's directory, then go run the main.go file. For example:

$ cd pixel-examples/platformer
$ go run main.go

Here are some screenshots from the examples!

Lights Platformer
Lights Platformer
Smoke Typewriter
Smoke Typewriter
Raycaster Starfield
Raycaster Starfield

Features

Here's the list of the main features in Pixel. Although Pixel is still under heavy development, there should be no major breakage in the API. This is not a 100% guarantee, though.

  • Fast 2D graphics
    • Sprites
    • Primitive shapes with immediate mode style IMDraw (circles, rectangles, lines, ...)
    • Optimized drawing with Batch
    • Text drawing with text package
  • Audio through a separate Beep library.
  • Simple and convenient API
    • Drawing a sprite to a window is as simple as sprite.Draw(window, matrix)
    • Wanna know where the center of a window is? window.Bounds().Center()
    • ...
  • Full documentation and tutorial
  • Works on Linux, macOS and Windows
  • Window creation and manipulation (resizing, fullscreen, multiple windows, ...)
  • Keyboard (key presses, text input) and mouse input without events
  • Well integrated with the Go standard library
    • Use "image" package for loading pictures
    • Use "time" package for measuring delta time and FPS
    • Use "image/color" for colors, or use Pixel's own color.Color format, which supports easy multiplication and a few more features
    • Pixel uses float64 throughout the library, compatible with "math" package
  • Geometry transformations with Matrix
    • Moving, scaling, rotating
    • Easy camera implementation
  • Off-screen drawing to Canvas or any other target (Batch, IMDraw, ...)
  • Fully garbage collected, no Close or Dispose methods
  • Full Porter-Duff composition, which enables
    • 2D lighting
    • Cutting holes into objects
    • Much more...
  • Pixel let's you draw stuff and do your job, it doesn't impose any particular style or paradigm
  • Platform and backend independent core
  • Core Target/Triangles/Picture pattern makes it easy to create new drawing targets that do arbitrarily crazy stuff (e.g. graphical effects)
  • Small codebase, ~5K lines of code, including the backend glhf package

Missing features

Pixel is in development and still missing few critical features. Here're the most critical ones.

  • Audio
  • Drawing text
  • Antialiasing (filtering is supported, though)
  • Advanced window manipulation (cursor hiding, window icon, ...)
  • Better support for Hi-DPI displays
  • Mobile (and perhaps HTML5?) backend
  • More advanced graphical effects (e.g. blur)
  • Tests and benchmarks

Implementing these features will get us to the 1.0 release. Contribute, so that it's as soon as possible!

Requirements

If you're using Windows and having trouble building Pixel, please check this guide on the wiki.

PixelGL backend uses OpenGL to render graphics. Because of that, OpenGL development libraries are needed for compilation. The dependencies are same as for GLFW.

The OpenGL version used is OpenGL 3.3.

  • On macOS, you need Xcode or Command Line Tools for Xcode (xcode-select --install) for required headers and libraries.
  • On Ubuntu/Debian-like Linux distributions, you need libgl1-mesa-dev and xorg-dev packages.
  • On CentOS/Fedora-like Linux distributions, you need libX11-devel libXcursor-devel libXrandr-devel libXinerama-devel mesa-libGL-devel libXi-devel packages.
  • See here for full details.

The combination of Go 1.8, macOS and latest XCode seems to be problematic as mentioned in issue #7. This issue is probably not related to Pixel. Upgrading to Go 1.8.1 fixes the issue.

Contributing

Pixel is in, let's say, mid-stage of development. Many of the important features are here, some are missing. That's why contributions are very important and welcome! All alone, I will be able to finish the library, but it'll take a lot of time. With your help, it'll take much less. I encourage everyone to contribute, even with just an idea. Especially welcome are issues and pull requests.

However, I won't accept everything. Pixel is being developed with thought and care. Each component was designed and re-designed multiple times. Code and API quality is very important here. API is focused on simplicity and expressiveness.

When contributing, keep these goals in mind. It doesn't mean that I'll only accept perfect pull requests. It just means that I might not like your idea. Or that your pull requests could need some rewriting. That's perfectly fine, don't let it put you off. In the end, we'll just end up with a better result.

Take a look at CONTRIBUTING.md for further information.

For any kind of discussion, feel free to use our Gitter community.

License

MIT

Documentation

Overview

Package pixel implements platform and backend agnostic core of the Pixel game development library.

It specifies the core Target, Triangles, Picture pattern and implements standard elements, such as Sprite, Batch, Vec, Matrix and RGBA in addition to the basic Triangles and Picture implementations: TrianglesData and PictureData.

Index

Constants

This section is empty.

Variables

View Source
var IM = Matrix{1, 0, 0, 1, 0, 0}

IM stands for identity matrix. Does nothing, no transformation.

View Source
var RGBAModel = color.ModelFunc(rgbaModel)

RGBAModel converts colors to RGBA format.

View Source
var ZV = Vec{0, 0}

ZV is a zero vector.

Functions

func Clamp added in v0.7.0

func Clamp(x, min, max float64) float64

Clamp returns x clamped to the interval [min, max].

If x is less than min, min is returned. If x is more than max, max is returned. Otherwise, x is returned.

Types

type BasicTarget

type BasicTarget interface {
	Target

	// SetMatrix sets a Matrix that every point will be projected by.
	SetMatrix(Matrix)

	// SetColorMask sets a color that will be multiplied with the TrianglesColor property of all
	// Triangles.
	SetColorMask(color.Color)
}

BasicTarget is a Target with additional basic adjustment methods.

type Batch

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

Batch is a Target that allows for efficient drawing of many objects with the same Picture.

To put an object into a Batch, just draw it onto it:

object.Draw(batch)

func NewBatch

func NewBatch(container Triangles, pic Picture) *Batch

NewBatch creates an empty Batch with the specified Picture and container.

The container is where objects get accumulated. Batch will support precisely those Triangles properties, that the supplied container supports. If you retain access to the container and change it, call Dirty to notify Batch about the change.

Note, that if the container does not support TrianglesColor, color masking will not work.

func (*Batch) Clear

func (b *Batch) Clear()

Clear removes all objects from the Batch.

func (*Batch) Dirty

func (b *Batch) Dirty()

Dirty notifies Batch about an external modification of it's container. If you retain access to the Batch's container and change it, call Dirty to notify Batch about the change.

container := &pixel.TrianglesData{}
batch := pixel.NewBatch(container, nil)
container.SetLen(10) // container changed from outside of Batch
batch.Dirty()        // notify Batch about the change

func (*Batch) Draw

func (b *Batch) Draw(t Target)

Draw draws all objects that are currently in the Batch onto another Target.

func (*Batch) MakePicture

func (b *Batch) MakePicture(p Picture) TargetPicture

MakePicture returns a specialized copy of the provided Picture that draws onto this Batch.

func (*Batch) MakeTriangles

func (b *Batch) MakeTriangles(t Triangles) TargetTriangles

MakeTriangles returns a specialized copy of the provided Triangles that draws onto this Batch.

func (*Batch) SetColorMask

func (b *Batch) SetColorMask(c color.Color)

SetColorMask sets a mask color used in the following draws onto the Batch.

func (*Batch) SetMatrix

func (b *Batch) SetMatrix(m Matrix)

SetMatrix sets a Matrix that every point will be projected by.

type ComposeMethod

type ComposeMethod int

ComposeMethod is a Porter-Duff composition method.

const (
	ComposeOver ComposeMethod = iota
	ComposeIn
	ComposeOut
	ComposeAtop
	ComposeRover
	ComposeRin
	ComposeRout
	ComposeRatop
	ComposeXor
	ComposePlus
	ComposeCopy
)

Here's the list of all available Porter-Duff composition methods. Use ComposeOver for the basic alpha blending.

func (ComposeMethod) Compose

func (cm ComposeMethod) Compose(a, b RGBA) RGBA

Compose composes two colors together according to the ComposeMethod. A is the foreground, B is the background.

type ComposeTarget

type ComposeTarget interface {
	BasicTarget

	// SetComposeMethod sets a Porter-Duff composition method to be used.
	SetComposeMethod(ComposeMethod)
}

ComposeTarget is a BasicTarget capable of Porter-Duff composition.

type Drawer

type Drawer struct {
	Triangles Triangles
	Picture   Picture
	// contains filtered or unexported fields
}

Drawer glues all the fundamental interfaces (Target, Triangles, Picture) into a coherent and the only intended usage pattern.

Drawer makes it possible to draw any combination of Triangles and Picture onto any Target efficiently.

To create a Drawer, just assign it's Triangles and Picture fields:

d := pixel.Drawer{Triangles: t, Picture: p}

If Triangles is nil, nothing will be drawn. If Picture is nil, Triangles will be drawn without a Picture.

Whenever you change the Triangles, call Dirty to notify Drawer that Triangles changed. You don't need to notify Drawer about a change of the Picture.

Note, that Drawer caches the results of MakePicture from Targets it's drawn to for each Picture it's set to. What it means is that using a Drawer with an unbounded number of Pictures leads to a memory leak, since Drawer caches them and never forgets. In such a situation, create a new Drawer for each Picture.

func (*Drawer) Dirty

func (d *Drawer) Dirty()

Dirty marks the Triangles of this Drawer as changed. If not called, changes will not be visible when drawing.

func (*Drawer) Draw

func (d *Drawer) Draw(t Target)

Draw efficiently draws Triangles with Picture onto the provided Target.

If Triangles is nil, nothing will be drawn. If Picture is nil, Triangles will be drawn without a Picture.

type Matrix

type Matrix [6]float64

Matrix is a 2x3 affine matrix that can be used for all kinds of spatial transforms, such as movement, scaling and rotations.

Matrix has a handful of useful methods, each of which adds a transformation to the matrix. For example:

pixel.IM.Moved(pixel.V(100, 200)).Rotated(pixel.ZV, math.Pi/2)

This code creates a Matrix that first moves everything by 100 units horizontally and 200 units vertically and then rotates everything by 90 degrees around the origin.

Layout is: [0] [2] [4] [1] [3] [5]

0   0   1  (implicit row)

func (Matrix) Chained

func (m Matrix) Chained(next Matrix) Matrix

Chained adds another Matrix to this one. All tranformations by the next Matrix will be applied after the transformations of this Matrix.

func (Matrix) Moved

func (m Matrix) Moved(delta Vec) Matrix

Moved moves everything by the delta vector.

func (Matrix) Project

func (m Matrix) Project(u Vec) Vec

Project applies all transformations added to the Matrix to a vector u and returns the result.

Time complexity is O(1).

func (Matrix) Rotated

func (m Matrix) Rotated(around Vec, angle float64) Matrix

Rotated rotates everything around a given point by the given angle in radians.

func (Matrix) Scaled

func (m Matrix) Scaled(around Vec, scale float64) Matrix

Scaled scales everything around a given point by the scale factor.

func (Matrix) ScaledXY

func (m Matrix) ScaledXY(around Vec, scale Vec) Matrix

ScaledXY scales everything around a given point by the scale factor in each axis respectively.

func (Matrix) String

func (m Matrix) String() string

String returns a string representation of the Matrix.

m := pixel.IM
fmt.Println(m) // Matrix(1 0 0 | 0 1 0)

func (Matrix) Unproject

func (m Matrix) Unproject(u Vec) Vec

Unproject does the inverse operation to Project.

It turns out that multiplying a vector by the inverse matrix of m can be nearly-accomplished by subtracting the translate part of the matrix and multplying by the inverse of the top-left 2x2 matrix, and the inverse of a 2x2 matrix is simple enough to just be inlined in the computation.

Time complexity is O(1).

type Picture

type Picture interface {
	// Bounds returns the rectangle of the Picture. All data is located witih this rectangle.
	// Querying properties outside the rectangle should return default value of that property.
	Bounds() Rect
}

Picture represents a rectangular area of raster data, such as a color. It has Bounds which specify the rectangle where data is located.

type PictureColor

type PictureColor interface {
	Picture
	Color(at Vec) RGBA
}

PictureColor specifies Picture with Color property, so that every position inside the Picture's Bounds has a color.

Positions outside the Picture's Bounds must return full transparent (Alpha(0)).

type PictureData

type PictureData struct {
	Pix    []color.RGBA
	Stride int
	Rect   Rect
}

PictureData specifies an in-memory rectangular area of pixels and implements Picture and PictureColor.

Pixels are small rectangles of unit size of form (x, y, x+1, y+1), where x and y are integers. PictureData contains and assigns a color to all pixels that are at least partially contained within it's Bounds (Rect).

The struct's innards are exposed for convenience, manual modification is at your own risk.

The format of the pixels is color.RGBA and not pixel.RGBA for a very serious reason: pixel.RGBA takes up 8x more memory than color.RGBA.

func MakePictureData

func MakePictureData(rect Rect) *PictureData

MakePictureData creates a zero-initialized PictureData covering the given rectangle.

func PictureDataFromImage

func PictureDataFromImage(img image.Image) *PictureData

PictureDataFromImage converts an image.Image into PictureData.

The resulting PictureData's Bounds will be the equivalent of the supplied image.Image's Bounds.

func PictureDataFromPicture

func PictureDataFromPicture(pic Picture) *PictureData

PictureDataFromPicture converts an arbitrary Picture into PictureData (the conversion may be lossy, because PictureData works with unit-sized pixels).

Bounds are preserved.

func (*PictureData) Bounds

func (pd *PictureData) Bounds() Rect

Bounds returns the bounds of this PictureData.

func (*PictureData) Color

func (pd *PictureData) Color(at Vec) RGBA

Color returns the color located at the given position.

func (*PictureData) Image

func (pd *PictureData) Image() *image.RGBA

Image converts PictureData into an image.RGBA.

The resulting image.RGBA's Bounds will be equivalent of the PictureData's Bounds.

func (*PictureData) Index

func (pd *PictureData) Index(at Vec) int

Index returns the index of the pixel at the specified position inside the Pix slice.

type RGBA

type RGBA struct {
	R, G, B, A float64
}

RGBA represents an alpha-premultiplied RGBA color with components within range [0, 1].

The difference between color.RGBA is that the value range is [0, 1] and the values are floats.

func Alpha

func Alpha(a float64) RGBA

Alpha returns a white RGBA color with the given alpha component.

func RGB

func RGB(r, g, b float64) RGBA

RGB returns a fully opaque RGBA color with the given RGB values.

A common way to construct a transparent color is to create one with RGB constructor, then multiply it by a color obtained from the Alpha constructor.

func ToRGBA

func ToRGBA(c color.Color) RGBA

ToRGBA converts a color to RGBA format. Using this function is preferred to using RGBAModel, for performance (using RGBAModel introduces additional unnecessary allocations).

func (RGBA) Add

func (c RGBA) Add(d RGBA) RGBA

Add adds color d to color c component-wise and returns the result (the components are not clamped).

func (RGBA) Mul

func (c RGBA) Mul(d RGBA) RGBA

Mul multiplies color c by color d component-wise (the components are not clamped).

func (RGBA) RGBA

func (c RGBA) RGBA() (r, g, b, a uint32)

RGBA returns alpha-premultiplied red, green, blue and alpha components of the RGBA color.

func (RGBA) Scaled

func (c RGBA) Scaled(scale float64) RGBA

Scaled multiplies each component of color c by scale and returns the result (the components are not clamped).

func (RGBA) Sub

func (c RGBA) Sub(d RGBA) RGBA

Sub subtracts color d from color c component-wise and returns the result (the components are not clamped).

type Rect

type Rect struct {
	Min, Max Vec
}

Rect is a 2D rectangle aligned with the axes of the coordinate system. It is defined by two points, Min and Max.

The invariant should hold, that Max's components are greater or equal than Min's components respectively.

func R

func R(minX, minY, maxX, maxY float64) Rect

R returns a new Rect with given the Min and Max coordinates.

Note that the returned rectangle is not automatically normalized.

func (Rect) Area added in v0.7.0

func (r Rect) Area() float64

Area returns the area of r. If r is not normalized, area may be negative.

func (Rect) Center

func (r Rect) Center() Vec

Center returns the position of the center of the Rect.

func (Rect) Contains

func (r Rect) Contains(u Vec) bool

Contains checks whether a vector u is contained within this Rect (including it's borders).

func (Rect) H

func (r Rect) H() float64

H returns the height of the Rect.

func (Rect) Intersect added in v0.7.0

func (r Rect) Intersect(s Rect) Rect

Intersect returns the maximal Rect which is covered by both r and s. Rects r and s must be normalized.

If r and s don't overlap, this function returns R(0, 0, 0, 0).

func (Rect) Moved

func (r Rect) Moved(delta Vec) Rect

Moved returns the Rect moved (both Min and Max) by the given vector delta.

func (Rect) Norm

func (r Rect) Norm() Rect

Norm returns the Rect in normal form, such that Max is component-wise greater or equal than Min.

func (Rect) Resized

func (r Rect) Resized(anchor, size Vec) Rect

Resized returns the Rect resized to the given size while keeping the position of the given anchor.

r.Resized(r.Min, size)      // resizes while keeping the position of the lower-left corner
r.Resized(r.Max, size)      // same with the top-right corner
r.Resized(r.Center(), size) // resizes around the center

This function does not make sense for resizing a rectangle of zero area and will panic. Use ResizedMin in the case of zero area.

func (Rect) ResizedMin

func (r Rect) ResizedMin(size Vec) Rect

ResizedMin returns the Rect resized to the given size while keeping the position of the Rect's Min.

Sizes of zero area are safe here.

func (Rect) Size

func (r Rect) Size() Vec

Size returns the vector of width and height of the Rect.

func (Rect) String

func (r Rect) String() string

String returns the string representation of the Rect.

r := pixel.R(100, 50, 200, 300)
r.String()     // returns "Rect(100, 50, 200, 300)"
fmt.Println(r) // Rect(100, 50, 200, 300)

func (Rect) Union added in v0.6.0

func (r Rect) Union(s Rect) Rect

Union returns the minimal Rect which covers both r and s. Rects r and s must be normalized.

func (Rect) W

func (r Rect) W() float64

W returns the width of the Rect.

type Sprite

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

Sprite is a drawable frame of a Picture. It's anchored by the center of it's Picture's frame.

Frame specifies a rectangular portion of the Picture that will be drawn. For example, this creates a Sprite that draws the whole Picture:

sprite := pixel.NewSprite(pic, pic.Bounds())

Note, that Sprite caches the results of MakePicture from Targets it's drawn to for each Picture it's set to. What it means is that using a Sprite with an unbounded number of Pictures leads to a memory leak, since Sprite caches them and never forgets. In such a situation, create a new Sprite for each Picture.

func NewSprite

func NewSprite(pic Picture, frame Rect) *Sprite

NewSprite creates a Sprite from the supplied frame of a Picture.

func (*Sprite) Draw

func (s *Sprite) Draw(t Target, matrix Matrix)

Draw draws the Sprite onto the provided Target. The Sprite will be transformed by the given Matrix.

This method is equivalent to calling DrawColorMask with nil color mask.

func (*Sprite) DrawColorMask added in v0.6.0

func (s *Sprite) DrawColorMask(t Target, matrix Matrix, mask color.Color)

DrawColorMask draws the Sprite onto the provided Target. The Sprite will be transformed by the given Matrix and all of it's color will be multiplied by the given mask.

If the mask is nil, a fully opaque white mask will be used, which causes no effect.

func (*Sprite) Frame

func (s *Sprite) Frame() Rect

Frame returns the current Sprite's frame.

func (*Sprite) Picture

func (s *Sprite) Picture() Picture

Picture returns the current Sprite's Picture.

func (*Sprite) Set

func (s *Sprite) Set(pic Picture, frame Rect)

Set sets a new frame of a Picture for this Sprite.

type Target

type Target interface {
	// MakeTriangles generates a specialized copy of the provided Triangles.
	//
	// When calling Draw method on the returned TargetTriangles, the TargetTriangles will be
	// drawn onto the Target that generated them.
	//
	// Note, that not every Target has to recognize all possible types of Triangles. Some may
	// only recognize TrianglesPosition and TrianglesColor and ignore all other properties (if
	// present) when making new TargetTriangles. This varies from Target to Target.
	MakeTriangles(Triangles) TargetTriangles

	// MakePicture generates a specialized copy of the provided Picture.
	//
	// When calling Draw method on the returned TargetPicture, the TargetPicture will be drawn
	// onto the Target that generated it together with the TargetTriangles supplied to the Draw
	// method.
	MakePicture(Picture) TargetPicture
}

Target is something that can be drawn onto, such as a window, a canvas, and so on.

You can notice, that there are no "drawing" methods in a Target. That's because all drawing happens indirectly through Triangles and Picture instances generated via MakeTriangles and MakePicture method.

type TargetPicture

type TargetPicture interface {
	Picture

	// Draw draws the supplied TargetTriangles (which must be generated by the same Target as
	// this TargetPicture) with this TargetPicture. The TargetTriangles should utilize the data
	// from this TargetPicture in some way.
	Draw(TargetTriangles)
}

TargetPicture is a Picture generated by a Target using MakePicture method. This Picture can be drawn onto that (no other) Target together with a TargetTriangles generated by the same Target.

The TargetTriangles specify where, shape and how the Picture should be drawn.

type TargetTriangles

type TargetTriangles interface {
	Triangles

	// Draw draws Triangles onto an associated Target.
	Draw()
}

TargetTriangles are Triangles generated by a Target with MakeTriangles method. They can be drawn onto that (no other) Target.

type Triangles

type Triangles interface {
	// Len returns the number of vertices. The number of triangles is the number of vertices
	// divided by 3.
	Len() int

	// SetLen resizes Triangles to len vertices. If Triangles B were obtained by calling Slice
	// method on Triangles A, the relationship between A and B is undefined after calling SetLen
	// on either one of them.
	SetLen(len int)

	// Slice returns a sub-Triangles of this Triangles, covering vertices in range [i, j).
	//
	// If Triangles B were obtained by calling Slice(4, 9) on Triangles A, then A and B must
	// share the same underlying data. Modifying B must change the contents of A in range
	// [4, 9). The vertex with index 0 at B is the vertex with index 4 in A, and so on.
	//
	// Returned Triangles must have the same underlying type.
	Slice(i, j int) Triangles

	// Update copies vertex properties from the supplied Triangles into this Triangles.
	//
	// Properies not supported by these Triangles should be ignored. Properties not supported by
	// the supplied Triangles should be left untouched.
	//
	// The two Triangles must have the same Len.
	Update(Triangles)

	// Copy creates an exact independent copy of this Triangles (with the same underlying type).
	Copy() Triangles
}

Triangles represents a list of vertices, where each three vertices form a triangle. (First, second and third is the first triangle, fourth, fifth and sixth is the second triangle, etc.)

type TrianglesColor

type TrianglesColor interface {
	Triangles
	Color(i int) RGBA
}

TrianglesColor specifies Triangles with Color property.

type TrianglesData

type TrianglesData []struct {
	Position  Vec
	Color     RGBA
	Picture   Vec
	Intensity float64
}

TrianglesData specifies a list of Triangles vertices with three common properties: TrianglesPosition, TrianglesColor and TrianglesPicture.

func MakeTrianglesData

func MakeTrianglesData(len int) *TrianglesData

MakeTrianglesData creates TrianglesData of length len initialized with default property values.

Prefer this function to make(TrianglesData, len), because make zeros them, while this function does the correct intialization.

func (*TrianglesData) Color

func (td *TrianglesData) Color(i int) RGBA

Color returns the color property of i-th vertex.

func (*TrianglesData) Copy

func (td *TrianglesData) Copy() Triangles

Copy returns an exact independent copy of this TrianglesData.

func (*TrianglesData) Len

func (td *TrianglesData) Len() int

Len returns the number of vertices in TrianglesData.

func (*TrianglesData) Picture

func (td *TrianglesData) Picture(i int) (pic Vec, intensity float64)

Picture returns the picture property of i-th vertex.

func (*TrianglesData) Position

func (td *TrianglesData) Position(i int) Vec

Position returns the position property of i-th vertex.

func (*TrianglesData) SetLen

func (td *TrianglesData) SetLen(len int)

SetLen resizes TrianglesData to len, while keeping the original content.

If len is greater than TrianglesData's current length, the new data is filled with default values ((0, 0), white, (0, 0), 0).

func (*TrianglesData) Slice

func (td *TrianglesData) Slice(i, j int) Triangles

Slice returns a sub-Triangles of this TrianglesData.

func (*TrianglesData) Update

func (td *TrianglesData) Update(t Triangles)

Update copies vertex properties from the supplied Triangles into this TrianglesData.

TrianglesPosition, TrianglesColor and TrianglesTexture are supported.

type TrianglesPicture

type TrianglesPicture interface {
	Triangles
	Picture(i int) (pic Vec, intensity float64)
}

TrianglesPicture specifies Triangles with Picture propery.

The first value returned from Picture method is Picture coordinates. The second one specifies the weight of the Picture. Value of 0 means, that Picture should be completely ignored, 1 means that is should be fully included and anything in between means anything in between.

type TrianglesPosition

type TrianglesPosition interface {
	Triangles
	Position(i int) Vec
}

TrianglesPosition specifies Triangles with Position property.

type Vec

type Vec struct {
	X, Y float64
}

Vec is a 2D vector type with X and Y coordinates.

Create vectors with the V constructor:

u := pixel.V(1, 2)
v := pixel.V(8, -3)

Use various methods to manipulate them:

  w := u.Add(v)
  fmt.Println(w)        // Vec(9, -1)
  fmt.Println(u.Sub(v)) // Vec(-7, 5)
  u = pixel.V(2, 3)
  v = pixel.V(8, 1)
  if u.X < 0 {
	     fmt.Println("this won't happen")
  }
  x := u.Unit().Dot(v.Unit())

func Lerp

func Lerp(a, b Vec, t float64) Vec

Lerp returns a linear interpolation between vectors a and b.

This function basically returns a point along the line between a and b and t chooses which one. If t is 0, then a will be returned, if t is 1, b will be returned. Anything between 0 and 1 will return the appropriate point between a and b and so on.

func Unit added in v0.7.0

func Unit(angle float64) Vec

Unit returns a vector of length 1 facing the given angle.

func V

func V(x, y float64) Vec

V returns a new 2D vector with the given coordinates.

func (Vec) Add added in v0.6.0

func (u Vec) Add(v Vec) Vec

Add returns the sum of vectors u and v.

func (Vec) Angle

func (u Vec) Angle() float64

Angle returns the angle between the vector u and the x-axis. The result is in range [-Pi, Pi].

func (Vec) Cross

func (u Vec) Cross(v Vec) float64

Cross return the cross product of vectors u and v.

func (Vec) Dot

func (u Vec) Dot(v Vec) float64

Dot returns the dot product of vectors u and v.

func (Vec) Len

func (u Vec) Len() float64

Len returns the length of the vector u.

func (Vec) Map

func (u Vec) Map(f func(float64) float64) Vec

Map applies the function f to both x and y components of the vector u and returns the modified vector.

u := pixel.V(10.5, -1.5)
v := u.Map(math.Floor)   // v is Vec(10, -2), both components of u floored

func (Vec) Normal added in v0.7.0

func (u Vec) Normal() Vec

Normal returns a vector normal to u. Equivalent to u.Rotated(math.Pi / 2), but faster.

func (Vec) Project added in v0.7.0

func (u Vec) Project(v Vec) Vec

Project returns a projection (or component) of vector u in the direction of vector v.

Behaviour is undefined if v is a zero vector.

func (Vec) Rotated

func (u Vec) Rotated(angle float64) Vec

Rotated returns the vector u rotated by the given angle in radians.

func (Vec) Scaled

func (u Vec) Scaled(c float64) Vec

Scaled returns the vector u multiplied by c.

func (Vec) ScaledXY

func (u Vec) ScaledXY(v Vec) Vec

ScaledXY returns the vector u multiplied by the vector v component-wise.

func (Vec) String

func (u Vec) String() string

String returns the string representation of the vector u.

u := pixel.V(4.5, -1.3)
u.String()     // returns "Vec(4.5, -1.3)"
fmt.Println(u) // Vec(4.5, -1.3)

func (Vec) Sub added in v0.6.0

func (u Vec) Sub(v Vec) Vec

Sub returns the difference betweeen vectors u and v.

func (Vec) To added in v0.7.0

func (u Vec) To(v Vec) Vec

To returns the vector from u to v. Equivalent to v.Sub(u).

func (Vec) Unit

func (u Vec) Unit() Vec

Unit returns a vector of length 1 facing the direction of u (has the same angle).

func (Vec) XY

func (u Vec) XY() (x, y float64)

XY returns the components of the vector in two return values.

Directories

Path Synopsis
Package imdraw implements a basic primitive geometry shape and pictured polygon drawing for Pixel with a nice immediate-mode-like API.
Package imdraw implements a basic primitive geometry shape and pictured polygon drawing for Pixel with a nice immediate-mode-like API.
Package pixelgl implements efficient OpenGL targets and utilities for the Pixel game development library, specifically Window and Canvas.
Package pixelgl implements efficient OpenGL targets and utilities for the Pixel game development library, specifically Window and Canvas.
Package text implements efficient text drawing for the Pixel library.
Package text implements efficient text drawing for the Pixel library.

Jump to

Keyboard shortcuts

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