oak

package module
v2.3.3-beta Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2020 License: Apache-2.0 Imports: 43 Imported by: 6

README

Oak

A pure Go game engine

GoDoc Go Report Card Code Coverage Mentioned in Awesome Go

Table of Contents

  1. Installation

  2. Motivation

  3. Features

  4. Support

  5. Quick Start

  6. Implementation and Examples

  7. Finished Games


Installation

go get -u github.com/oakmound/oak/v2/...

Or in GOPATH mode (not using go modules):

go get -u github.com/oakmound/oak/...

Motivation

The initial version of oak was made to support Oakmound Studio's game, Agent Blue, and was developed in parallel. Oak supports Windows with no dependencies and Linux with limited audio dependencies. We don't own a machine to check with, but hypothetically it supports OSX as well. We hope that users will be able to make great pure Go games with oak and welcome improvements.

Because Oak wants to have as few non-Go dependencies as possible, Oak does not use OpenGL or GLFW. We're open to adding support for these in the future for performance gains, but we always want an alternative that requires zero or near-zero dependencies.

Features

  1. Window Rendering
    • Windows and key events forked from shiny
    • Logical frame rate distinct from Draw rate
    • Fullscreen, Window Positioning support
    • Auto-scaling for screen size changes
  2. Image Management
    • render.Renderable interface
    • Sprite Sheet Batch Loading at startup
    • Manipulation
      • render.Modifiable interface
      • Built in Transformations and Filters
      • Some built-ins via gift
      • Extensible Modification syntax func(image.Image) *image.RGBA
    • Built in Renderable types covering common use cases
      • Sprite, Sequence, Switch, Composite
      • Primitive builders, ColorBox, Line, Bezier
      • History-tracking Reverting
    • Primarily 2D
  3. Particle System
    • Click to see gif captured in examples/particle-demo

      particles!

  4. Mouse Handling
    • Click Collision
    • MouseEnter / MouseExit reaction events
    • Drag Handling
  5. Joystick Support
    • Click to see gif captured in examples/joystick-viz

      particles!

  6. Audio Support
    • Positional filters to pan and scale audio based on a listening position
  7. Collision
    • Collision R-Tree forked from rtreego
    • 2D Raycasting
    • Collision Spaces
      • Attachable to Objects
      • Auto React to collisions through events
      • OnHit bindings func(s1,s2 *collision.Space)
      • Start/Stop collision with targeted objects
  8. 2D Physics System
    • Vectors
      • Attachable to Objects / Renderables
      • Friction
  9. Event Handler, Bus
    • PubSub system: event.CID can Bind(fn,eventName) and Trigger(eventName) events
  10. Shaping
    • Convert shapes into:
      • Containment checks
      • Outlines
      • 2D arrays
  11. Custom Console Commands
  12. Logging
    • Swappable with custom implementations
    • Default Implementation: 4 log levels, writes to file and stdout

Support

For discussions not significant enough to be an Issue or PR, see the #oak channel on the gophers slack.

Quick Start

This is an example of the most basic oak program:


oak.Add("firstScene",
    // Initialization function
    func(prevScene string, inData interface{}) {}, 
    // Loop to continue or stop the current scene
    func() bool {return true}, 
    // Exit to transition to the next scene
    func() (nextScene string, result *scene.Result) {return "firstScene", nil}) 
oak.Init("firstScene")

See the examples folder for longer demos, godoc for reference documentation, and the wiki for more guided feature sets, tutorials and walkthroughs.

Implementation and Examples

Platformer

Platformer

Build up to having a simple platforming game by doing the following: Setup a character, get it to move, set basic gravity, get it to jump, make it only jump on solid ground, put it all together.


char := entities.NewMoving(100, 100, 16, 32,
	render.NewColorBox(16, 32, color.RGBA{255, 0, 0, 255}),
nil, 0, 0)

char.Bind(func(id int, nothing interface{}) int {
	char := event.GetEntity(id).(*entities.Moving)

	// Move left and right with A and D
	if oak.IsDown(key.A) {
		char.Delta.SetX(-char.Speed.X())
	} else if oak.IsDown(key.D) {
		char.Delta.SetX(char.Speed.X())
	} else {
		char.Delta.SetX(0)
	}
	oldX, oldY := char.GetPos()
    char.ShiftPos(char.Delta.X(), char.Delta.Y())
	return 0
}, event.Enter)
Top Down Shooter

Learn to use the collision library and make short term shots that collide with the entites marked with collision labels.

Shoota

Radar

Often times you might want to create a minimap or a radar for a game, check out this example for a barebones implementation

Radar

Slideshow

A different way to use the oak engine.

Slideshow

Examples of Finished Games

Agent Blue

AgentBlue

Fantastic Doctor

Fantastic Overview

Fantastic Overview 2

Jeremy The Clam

Clammy

Documentation

Overview

Package oak is a game engine. It provides scene control, control over windows and what is drawn to them, propagates regular events to evaluate game logic, and so on. Oak also serves as the top level package and contains all the subdirectories that make up the Oak engine.

Example

Use oak to display a scene with a single movable character

Add("basicScene", func(string, interface{}) {

	char := entities.NewMoving(100, 100, 16, 32,
		render.NewColorBox(16, 32, color.RGBA{255, 0, 0, 255}),
		nil, 0, 0)
	render.Draw(char.R)

}, func() bool {
	return true
}, func() (string, *scene.Result) {
	return "basicScene", nil
})
Init("basicScene")
Output:

Index

Examples

Constants

View Source
const (
	// DefaultSeed is a key int64 sent in to SeedRNG
	// used to indicate that the seed function should just
	// do the default operation for seeding, using the current
	// time.
	DefaultSeed int64 = iota
)

Variables

View Source
var (
	// SetupConfig is the config struct read from at initialization time
	// when oak starts. When oak.Init() is called, the variables behind
	// SetupConfig are passed to their appropriate places in the engine, and
	// afterword the variable is unused.
	SetupConfig Config

	// SetupFullscreen defines whether the initial screen will start as a fullscreen
	// window. This variable will go away when oak reaches 3.0, and it will be folded
	// into the config struct.
	SetupFullscreen bool

	// SetupBorderless defines whether the initial screen will start as a borderless
	// window. This variable will go away when oak reaches 3.0, and it will be folded
	// into the config struct.
	SetupBorderless bool

	// SetupTopMost defines whether the initial screen will start on top of other
	// windows (even when out of focus). This variable will go away when oak reaches
	// 3.0, and it will be folded into the config struct.
	SetupTopMost bool
)
View Source
var (
	// Background is the uniform color drawn to the screen in between draw frames
	Background = image.Black
	// DrawTicker is the parallel to LogicTicker to set the draw framerate
	DrawTicker *timing.DynamicTicker
)
View Source
var (

	// ScreenWidth is the width of the screen
	ScreenWidth int
	// ScreenHeight is the height of the screen
	ScreenHeight int

	// FrameRate is the current logical frame rate.
	// Changing this won't directly effect frame rate, that
	// requires changing the LogicTicker, but it will take
	// effect next scene
	FrameRate int

	// DrawFrameRate is the equivalent to FrameRate for
	// the rate at which the screen is drawn.
	DrawFrameRate int
)
View Source
var (
	// ColorPalette is the current color palette oak is set to conform to. Modification of this
	// value directly will not effect oak's palette, use SetPalette instead. If SetPallete is never called,
	// this is the zero value ([]Color of length 0).
	ColorPalette color.Palette
)
View Source
var (
	// DefShaker is the global default shaker, used when oak.ShakeScreen is called.
	DefShaker = ScreenShaker{false, floatgeom.Point2{1.0, 1.0}}
)
View Source
var (
	DefaultDriver = driver.Main
)

Driver alternatives

View Source
var InitDriver = DefaultDriver

InitDriver is the driver oak will call during initialization

View Source
var (

	// LoadingR is a renderable that is displayed during loading screens.
	LoadingR render.Renderable
)
View Source
var (
	// SceneMap is a global map of scenes referred to when scenes advance to
	// determine what the next scene should be.
	// It can be replaced or modified so long as these modifications happen
	// during a scene or before oak has started.
	SceneMap = scene.NewMap()
)
View Source
var (
	// UseAspectRatio determines whether new window changes will distort or
	// maintain the relative width to height ratio of the screen buffer.
	UseAspectRatio = false
)
View Source
var (
	// ViewPos represents the point in the world which the viewport is anchored at.
	ViewPos = image.Point{}
)

Functions

func Add

func Add(name string, start scene.Start, loop scene.Loop, end scene.End) error

Add is shorthand for oak.SceneMap.Add /scene#Add

Example
Add("basicScene", func(string, interface{}) { // Whatever you want to do while in the scene
}, func() bool { // return whether this scene should loop or exit on end
	return true
}, func() (string, *scene.Result) { // What scene to progress to, make sure its set up!
	return "sceneToBeImplemented", nil
})
Output:

func AddCommand

func AddCommand(s string, fn func([]string)) error

AddCommand adds a console command to call fn when '<s> <args>' is input to the console. fn will be called with args split on whitespace.

Example

Use AddCommand to grant access to command line commands. Often used to toggle debug modes.

debug := true
AddCommand("SetDebug", func(args []string) {

	if len(args) == 0 {
		debug = !debug
	}
	switch args[0][:1] {
	case "t", "T":
		debug = true
	case "f", "F":
		debug = false
	}

})
Output:

func AddScene

func AddScene(name string, s scene.Scene) error

AddScene is shorthand for oak.SceneMap.AddScene

Example

Addscene lets a central package manage a set of scenes across subpackages such as in weekly87 Note the example wont work because there is nothing

AddScene("scene1", getBasicScene())
AddScene("scene2", getBasicScene())
Output:

func BindKey

func BindKey(key string, binding string)

BindKey binds a name to be triggered when this key is triggered

func BindKeyBindings

func BindKeyBindings(r io.Reader) error

BindKeyBindings loads and binds KeyBindings at once. It maintains existing keybindings not a part of the input reader.

func BindKeys

func BindKeys(bindings KeyBindings)

BindKeys loops over and binds all pairs in the input KeyBindings

func ChangeWindow

func ChangeWindow(width, height int)

ChangeWindow sets the width and height of the game window. Although exported, calling it without a size event will probably not act as expected.

func ClearCommand

func ClearCommand(s string)

ClearCommand clears an existing debug command by key: <s>

func ClearScreenFilter

func ClearScreenFilter()

ClearScreenFilter resets the draw function to no longer filter the screen before publishing it to the window.

func ForceAddCommand

func ForceAddCommand(s string, fn func([]string)) func([]string)

ForceAddCommand adds or overwrites a console command to call fn when '<s> <args>' is input to the console. fn will be called with args split on whitespace. If a command is overwritten the overwritten command will be returned.

func GetDebugKeys

func GetDebugKeys() []string

GetDebugKeys returns the current debug console commands as a string array

func GetKeyBind

func GetKeyBind(key string) string

GetKeyBind returns either whatever name has been bound to a key or the key if nothing has been bound to it. Todo: this should be a var function that starts out as "return key", and only becomes this function when a binding is made.

func GetScreen

func GetScreen() *image.RGBA

GetScreen returns the current screen as an rgba buffer

func GetViewportBounds

func GetViewportBounds() (x1, y1, x2, y2 int, ok bool)

GetViewportBounds reports what bounds the viewport has been set to, if any.

func Init

func Init(firstScene string)

Init initializes the oak engine. It spawns off an event loop of several goroutines and loops through scenes after initialization.

func IsDown

func IsDown(key string) (k bool)

IsDown returns whether a key is held down

func IsHeld

func IsHeld(key string) (k bool, d time.Duration)

IsHeld returns whether a key is held down, and for how long

func LoadConf

func LoadConf(filePath string) error

LoadConf loads a config file, that could exist inside oak's binary data storage (see fileutil), to SetupConfig

func LoadConfData

func LoadConfData(r io.Reader) error

LoadConfData takes in an io.Reader and decodes it to SetupConfig

func MoveWindow

func MoveWindow(x, y, w, h int) error

MoveWindow sets the position of a window to be x,y and it's dimensions to w,h If the window does not support being positioned, it will report as such.

func Quit

func Quit()

Quit sends a signal to the window to close itself, ending oak.

func RecordGIF

func RecordGIF(hundredths int) (stop func() *gif.GIF)

RecordGIF will start recording frames via screen shots with the given time delay (in 1/100ths of a second) between frames. When the returned stop function is called, the frames will be compiled into a gif.

func RemoveViewportBounds

func RemoveViewportBounds()

RemoveViewportBounds removes restrictions on the viewport's movement. It will not cause ViewPos to update immediately.

func ResetCommands

func ResetCommands()

ResetCommands will throw out all existing debug commands from the debug console.

func ScreenShot

func ScreenShot() *image.RGBA

ScreenShot takes a snap shot of the window's image content. ScreenShot is not safe to call while an existing ScreenShot call has yet to finish executing. This could change in the future.

func SeedRNG

func SeedRNG(inSeed int64)

SeedRNG seeds go's random number generator and logs the seed set to file.

func SetAspectRatio

func SetAspectRatio(xToY float64)

SetAspectRatio will enforce that the displayed window does not distort the input screen away from the given x:y ratio. The screen will not use these settings until a new size event is received from the OS.

func SetBinaryPayload

func SetBinaryPayload(payloadFn func(string) ([]byte, error), dirFn func(string) ([]string, error))

SetBinaryPayload just sets some public fields on packages that require access to binary functions as alternatives to os file functions. This is no longer necessary, as a single package uses these now.

func SetBorderless

func SetBorderless(on bool) error

SetBorderless attempts to set the local oak window to have no border. If the window does not support this functionaltiy, it will report as such.

func SetFullScreen

func SetFullScreen(on bool) error

SetFullScreen attempts to set the local oak window to be full screen. If the window does not support this functionality, it will report as such.

func SetKeyBindings

func SetKeyBindings(r io.Reader) error

SetKeyBindings removes all existing keybindings and then binds all bindings within the input reader.

func SetLang

func SetLang(s string)

SetLang parses a string as a language

func SetLogicHandler

func SetLogicHandler(h event.Handler)

SetLogicHandler swaps the logic system of the engine with some other implementation. If this is never called, it will use event.DefaultBus

func SetPalette

func SetPalette(palette color.Palette)

SetPalette tells oak to conform the screen to the input color palette before drawing.

func SetScreen

func SetScreen(x, y int)

SetScreen sends a signal to the draw loop to set the viewport to be at x,y

func SetScreenFilter

func SetScreenFilter(screenFilter mod.Filter)

SetScreenFilter will filter the screen by the given modification function prior to publishing the screen's rgba to be displayed.

func SetTopMost

func SetTopMost(on bool) error

SetTopMost attempts to set the local oak window to stay on top of other windows. If the window does not support this functionality, it will report as such.

func SetViewportBounds

func SetViewportBounds(x1, y1, x2, y2 int)

SetViewportBounds sets the minimum and maximum position of the viewport, including screen dimensions

func ShakeScreen

func ShakeScreen(dur time.Duration)

ShakeScreen will Shake using the package global DefShaker

func UnbindAllKeys

func UnbindAllKeys()

UnbindAllKeys clears the contents of the oak's keybindings.

func UnbindKey

func UnbindKey(key string)

UnbindKey removes the binding for the given key in oak's keybindings. Does nothing if the key is not already bound.

func ViewVector

func ViewVector() physics.Vector

ViewVector returns ViewPos as a Vector

Types

type Assets

type Assets struct {
	AssetPath string `json:"assetPath"`
	AudioPath string `json:"audioPath"`
	ImagePath string `json:"imagePath"`
	FontPath  string `json:"fontPath"`
}

Assets is a json type storing paths to different asset folders

type Borderlesser

type Borderlesser interface {
	SetBorderless(bool) error
}

A Borderlesser is a window that can have its border removed or replaced after removal.

type Config

type Config struct {
	Assets              Assets `json:"assets"`
	Debug               Debug  `json:"debug"`
	Screen              Screen `json:"screen"`
	Font                Font   `json:"font"`
	FrameRate           int    `json:"frameRate"`
	DrawFrameRate       int    `json:"drawFrameRate"`
	Language            string `json:"language"`
	Title               string `json:"title"`
	BatchLoad           bool   `json:"batchLoad"`
	GestureSupport      bool   `json:"gestureSupport"`
	LoadBuiltinCommands bool   `json:"loadBuiltinCommands"`
	TrackInputChanges   bool   `json:"trackInputChanges"`
}

Config stores initialization settings for oak.

type Debug

type Debug struct {
	Filter string `json:"filter"`
	Level  string `json:"level"`
}

Debug is a json type storing the starting debug filter and level

type Driver

type Driver func(f func(screen.Screen))

A Driver is a function which can take in our lifecycle function and initialize oak with the OS interfaces it needs.

type Font

type Font struct {
	Hinting string  `json:"hinting"`
	Size    float64 `json:"size"`
	DPI     float64 `json:"dpi"`
	File    string  `json:"file"`
	Color   string  `json:"color"`
}

Font is a json type storing the default font settings

type FullScreenable

type FullScreenable interface {
	SetFullScreen(bool) error
}

FullScreenable defines windows that can be set to full screen.

type InputType

type InputType int

InputType expresses some form of input to the engine to represent a player

const (
	KeyboardMouse InputType = iota
	Joystick      InputType = iota
)

Supported Input Types

var (
	// MostRecentInput tracks what input type was most recently detected.
	// This is only updated if TrackInputChanges is true in the config at startup
	MostRecentInput InputType
)

type KeyBindings

type KeyBindings map[string]string

KeyBindings map input keys to meaningful names, so code can be built around those meaningufl names and users can easily rebind which keys do what.

func LoadKeyBindings

func LoadKeyBindings(r io.Reader) (KeyBindings, error)

LoadKeyBindings converts a reader into a map of keys to meaningful names. It expects a simple .toml syntax, of key = "value" pairs per line. The resulting KeyBindings will have the keys and values reversed, so `MoveUp = "W"` will correspond to kb["W"] = "MoveUp"

type Language

type Language int

Language is hypothetically something games might care about in their text work: Consider moving this to oakerr, and also moving all strings to oakerr so messages output by the engine are localized.

const (
	ENGLISH Language = iota
	GERMAN
)

Lang enumerator

var (
	// Lang is the current langugae
	Lang Language
)

type MovableWindow

type MovableWindow interface {
	MoveWindow(x, y, w, h int32) error
}

MovableWindow defines windows that can have their position set

type Screen

type Screen struct {
	X      int `json:"X"`
	Y      int `json:"Y"`
	Height int `json:"height"`
	Width  int `json:"width"`
	Scale  int `json:"scale"`
}

Screen is a json type storing the starting screen width and height

type ScreenShaker

type ScreenShaker struct {
	Random    bool
	Magnitude floatgeom.Point2
}

A ScreenShaker knows how to shake a screen by a (or up to a) given magnitude. If Random is true, the Shaker will shake up to the (negative or positive) magnitude of each the X and Y axes. Otherwise, it will oscillate between negative magnitude and positive magnitude.

func (*ScreenShaker) Shake

func (ss *ScreenShaker) Shake(dur time.Duration)

Shake shakes the screen based on this ScreenShaker's attributes. See DefShaker for an example shaker setup

type TopMoster

type TopMoster interface {
	SetTopMost(bool) error
}

A TopMoster is a window that can be configured to stay on top of other windows.

Directories

Path Synopsis
alg
Package alg stores useful algorithms and math functions
Package alg stores useful algorithms and math functions
floatgeom
Package floatgeom stores primitives for floating point geometry
Package floatgeom stores primitives for floating point geometry
intgeom
Package intgeom stores primitives for integer geometry
Package intgeom stores primitives for integer geometry
Package audio provides audio types, font types for filtering audio reactively, and channels to allow constant audio play signals to be restricted to play at variable frequencies.
Package audio provides audio types, font types for filtering audio reactively, and channels to allow constant audio play signals to be restricted to play at variable frequencies.
Package collision provides collision tree and space structures along with hit detection functions on spaces.
Package collision provides collision tree and space structures along with hit detection functions on spaces.
ray
Package ray holds utilities for performing iterative collision checks or raycasts
Package ray holds utilities for performing iterative collision checks or raycasts
Package dlog provides logging functions with caller file and line information, logging levels and level and text filters.
Package dlog provides logging functions with caller file and line information, logging levels and level and text filters.
Package entities stores useful object and entity types, such as positions and renderables, collision spaces and renderables, and delta / speed vectors built into the above types.
Package entities stores useful object and entity types, such as positions and renderables, collision spaces and renderables, and delta / speed vectors built into the above types.
Package event propagates events through entities with given caller IDs.
Package event propagates events through entities with given caller IDs.
examples
Package fileutil provides functionality to subvert os and ioutil calls when needed for particular operating systems (js) or runtimes (asset data packaged into a binary)
Package fileutil provides functionality to subvert os and ioutil calls when needed for particular operating systems (js) or runtimes (asset data packaged into a binary)
Package joystick provides utilities for querying and reacting to joystick or gamepad inputs.
Package joystick provides utilities for querying and reacting to joystick or gamepad inputs.
Package key enumerates keystrings for use in bindings
Package key enumerates keystrings for use in bindings
Package mouse handles the propagation of mouse events though clickable regions.
Package mouse handles the propagation of mouse events though clickable regions.
Package oakerr stores errors returned throughout oak.
Package oakerr stores errors returned throughout oak.
Package physics provides vector types and operations to perform math and simple physics on those types.
Package physics provides vector types and operations to perform math and simple physics on those types.
Package render provides several types of renderable entities which are used throughout the code base In addition to entities the package also provides utilities to load images from files and load images from parts of files as well as draw them.
Package render provides several types of renderable entities which are used throughout the code base In addition to entities the package also provides utilities to load images from files and load images from parts of files as well as draw them.
mod
Package mod stores modification functions for images
Package mod stores modification functions for images
particle
Package particle provides options for generating renderable particle sources.
Package particle provides options for generating renderable particle sources.
Package scene stores definitions for interacting with game loop scenes
Package scene stores definitions for interacting with game loop scenes
Package shape provides types to satisfy the Shape interface, which allows for containment and outline checks on two dimensional shapes.
Package shape provides types to satisfy the Shape interface, which allows for containment and outline checks on two dimensional shapes.
Package timing provides utilities for time
Package timing provides utilities for time

Jump to

Keyboard shortcuts

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