gfx

package module
v0.0.0-...-22d950b Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2024 License: MIT Imports: 35 Imported by: 1

README

Run Tests Report Card Reference

2D/3D Graphics Module for Go

Overview

This is a relatively simple 2D/3D graphics library originally written with a focus on rendering sensor data in realtime, without affecting the routine/process responsible for communicating with the sensor (which could be a high-frequency, time-sensitive process, etc.) The underlying graphics framework is OpenGL, with window management and user input handled using GLFW.


Features

Dead-simple API for rendering shapes, text and more!
Common UI controls: Label, Button, Slider, Checkbox, RadioButton
Canvas and Brush controls for end-user painting
Performant line graph intended for realtime signal analysis
Hi/low/band-pass and custom (user-defined) filtering
FFT and custom (user-defined) transformers
Ambient/diffuse/specular/emissive/transparent lighting
Diffuse/normal/specular map support
Custom struct-to-shader uniform/buffer binding
Custom camera, lighting, and viewport support
Wavefront OBJ/MTL importer
Text rendering using TrueType fonts
Multiple/transparent/borderless windows
Interface-based and object-oriented for flexible customization

Prerequisites

Developed/tested on:

Operating System Kernel
Ubuntu Base 22.04.3 + GNOME 42.9 / X11 5.15.0-86-lowlatency
Ubuntu Base 24.04.0 + GNOME 46.0 / Wayland 6.8.0-31-lowlatency

Compiler (Go v1.20):

 wget https://go.dev/dl/go1.20.10.linux-amd64.tar.gz
 sudo tar -C /usr/local -xzf go1.20.10.linux-amd64.tar.gz
 export PATH=$PATH:/usr/local/go/bin

For more assistance installing Go, check out the docs.

Install required packages (Debian/Ubuntu):

sudo apt install libgl1-mesa-dev libglfw3-dev libfreetype6-dev  

If using Wayland instead of X11, you will also need to install these packages:

sudo apt install pkg-config libxcursor-dev libxinerama-dev libxi-dev libxxf86vm-dev

Testing

Running the included tests is a great way to ensure your system has the required hardware and prerequisites installed to use this library. Simply navigate to the _test directory and execute the run_tests.sh script:

cd _test
./run_tests.sh

Included is a mix of unit and smoke tests, the latter of which requires the creation of windows to render testable scenes to the framebuffer. Obviously, those tests will only succeed when executing in the context of a GUI-enabled OS environment supported by GLFW or, as in the case when the tests run as a GitHub Action, when rendering to a virtual framebuffer using a service like Xvfb.


Examples

If you prefer to learn by example, check out the code in the examples directory. Most, if not all, of the features are flexed in those examples.

Each example application assumes it is running from that example's root directory, which is the one containing the main.go file. In that directory is also a script named run.sh, which you can execute to run the application or, if you prefer to run/debug using an IDE, just ensure that you set the working directory accordingly in the "run configuration" or "debug settings" of your IDE when running examples that load assets using relative paths to files (and not references to embedded files, as done in other examples).


Usage

Initialization, Running & Cleanup

Before doing anything else (especially before spawning a new Go routine), you should initialize the package by calling the gfx.Init function:

if err := gfx.Init(); err != nil {
    panic(err)
}  

Most notably, that will initialize GLFW, which is necessary for most of the things you can do with this library. Since it's required to initialize GLFW from the application's main thread, so too must it be required to call gfx.Init() from the main thread. To facilitate that requirement, given that the Go runtime decides which underlying OS threads our Go routines will run on, it is highly recommended to call gfx.Init() as soon as possible, which requires the importing of this package, therefore triggering the runtime to automatically invoke gfx.init() (the unexported version) on application startup, before executing main(). The gfx.init function calls runtime.LockOSThread(), which will ensure that the thread assigned to the currently running Go routine will not be reassigned to another routine...the hope being that thread is the main thread and we can then ensure all subsequent OpenGL/GLFW calls are made on the Go routine to which the main thread was assigned.

Closing the package results in closing any windows that were initialized and terminating GLFW. This can be done by calling the gfx.Close function:

gfx.Close()

Unlike with initialization, you can call that function from any routine, at any time, but in many cases you can simply have it deferred until returning from main(). If closed, you must call gfx.Init() again if you need to use the package once more.

In between initializing and closing the package, you'll be running the gfx "engine," managing window instances and the objects/services/assets associated with each. The details of the latter will be covered more later, but running the engine simply means calling the gfx.Run function from the "main" routine while the latter usually happens on worker routines. The engine then updates/renders any windows you have spawned at an interval based on the target framerate (see Global Configuration). That process represents the main application loop and will execute indefinitely, until one of the following conditions is met:

  • any primary window is closed (see Window Destruction)
  • gfx.Close() is called
  • the context.Context passed to gfx.Run() is canceled

The typical pattern for using this library will look like:

package main

import (
    "context"
    "github.com/tonybillings/gfx"
)

func main() {
     if err := gfx.Init(); err != nil {
         panic(err)
     }
     defer gfx.Close()

     // Configure the window(s)
     // Load assets and add to the window's asset library
     // Configure window services/objects
     // Add services/objects to the window(s)
     // Initialize the window(s)
     // Start any worker routines
     // Run the engine, blocking until the context is canceled:
     gfx.Run(context.WithCancel(context.Background()))
     // ...but store a reference to the cancel function if 
     // you plan to stop the engine that way!
}

From this point on in the document, it's assumed that the code presented is executed after gfx.Init() but before gfx.Run() is called.

Global Configuration

At the package level, there are currently only two configuration parameters:

Parameter Default Setter Description
Target Framerate 60 gfx.SetTargetFramerate(int) The target framerate, in frames per second*.
V-Sync true gfx.SetVSyncEnabled(bool) If enabled, prevents "screen tearing" by setting the swap interval to 1.

*Limiting the framerate, or frames per second (FPS), will result in putting the main thread to sleep so that other, higher-priority threads/processes (such as those acquiring/timestamping samples from a sensor, etc) can work. Sleeping is not a precise action, nor is the implementation of the framerate-limiting logic found in this module, so do not expect the effective FPS to be precisely on target-- even in optimal conditions. To disable framerate limiting, the only option at this time is to just use a high target framerate setting (e.g., 9999). With V-Sync enabled, the update/tick rate for windows will not exceed the current refresh rate of the monitor.

Window Creation

All exported gfx types should be created using their associated "New-" function and windows are no different. The type for them is Window and one can be created via the gfx.NewWindow function:

win := gfx.NewWindow()
Window Configuration

Configuration of most types can be done via a series of chained method calls, like so:

win := gfx.NewWindow().
    SetTitle("This text appears in the window's title bar, if not a borderless window").
    SetWidth(1920).
    SetHeight(1080).
    SetClearColor(gfx.Black) // can use an out-of-the-box color or any color.RGBA 

By default, windows will initially be displayed at the center of the screen, however you can always specify the window's position via SetPosition() (either before or after the window has been displayed). Any of the configuration functions (that begin with "Set-") can be called after the window has been created/displayed, meaning you can change those aspects of the window at any time. Some configuration options must be specified at the time of creation, however, and those options are referred to as window "hints" (as per GLFW lexicon) and must be passed into the gfx.NewWindow function.

Currently, the following hints are supported:

Hint Default Description
Borderless false If true, the window will not be "decorated," meaning it will not have a title bar or border.
Resizeable false If true, the maximize button in the title bar will not be enabled/visible and resizing via border gripping/dragging is disabled*.
Multi-sampling false If true, will enable anti-aliasing via OpenGL's native MSAA feature, with the sample count set to 4.

*Resizing and going fullscreen is still possible programmatically and the Window type provides functions for those actions.

Example creating a borderless window with 4xMSAA enabled:

borderless := true
resizeable := false
msaa := true
win := gfx.NewWindow(gfx.NewWindowHints(borderless, resizable, msaa))

More configuration options are available for Window and are demonstrated in the included examples and tests.

Window Initialization

Like most gfx types, Window instances must be initialized and like all life-cycle functions (see related section), should be done on the main thread. That particular concern is handled for you by the gfx.InitWindowAsync function, which you can call from any routine, at any time, to have a window initialized:

gfx.InitWindowAsync(win)

Note the "-Async" suffix, which is indication that the function will not block but will result in queuing work to be performed on another routine (in this case, the one locked to the main thread). If you need to perform some action as soon as the window is initialized, you can do this:

gfx.InitWindowAsync(win)
<-win.ReadyChan()

Assuming the engine is running (gfx.Run() has been called), once the window has been initialized, it will be displayed on the screen (or not, depending on how it was configured), and will be updated/ticked as per the target framerate.

Window Destruction

Explicitly closing/destroying a window is only necessary in a multi-window scenario, when additional windows are presented but at some point may need to be closed without that resulting in closing the entire application. By default, every window has "primary" status, meaning that closing such a window, if it has been initialized, will result in the application closing. To prevent that behavior, such as when additional windows are used for pop-up/modal dialogs, pass true to the SetSecondary function provided by Window:

msgWin.SetSecondary(true) // can call any time

And to close:

gfx.CloseWindowAsync(msgWin) // can call from any routine

Note that calling gfx.Close() will result in closing all remaining initialized windows, ensuring the Close function is called for all objects/services/assets associated with them before returning.

Life-cycle Functions
Name Description
Init Called once, but implementations should be idempotent; may change the state of the OpenGL context or result in allocation of RAM/VRAM, etc.
Update Called during each window "tick," as per the target framerate; will usually be passed the delta-time in microseconds and will not do anything if the object is disabled.
Draw Called after Update; will usually be passed the delta-time in microseconds and will not render anything if the object is invisible.
Close Called once, but implementations should be idempotent; should release reserved RAM/VRAM, destroy/unbind OpenGL resources, etc.

Life-cycle functions are those found throughout the gfx package with the names Init, Update, Draw, and Close. Except for the package-level functions already introduced, gfx.Init and gfx.Close, these special functions should not be directly invoked as some must be executed on the main thread and many in coordination with other changes being made to the active OpenGL context. These functions are defined in many interfaces and are only exported so that you can provide custom implementations (see Advanced Usage). Note that while their signatures may vary slightly, with different arguments and return types, it's their name that identifies them as being a life-cycle function.

Objects & Services

Many of the gfx types implement the Object interface, which includes the Init, Update, and Close functions; the DrawableObject interface adds the Draw function. Types implementing these interfaces are usually added to Window instances for full life-cycle management. The Window type also provides functions for ad-hoc initialization/closure, including both synchronous and asynchronous variants:

// Let the window manage the object, updating/drawing it each tick 
// and closing it when the window closes
quad := gfx.NewQuad()
win.AddObject(quad)

// But if you need to close it sooner:
win.CloseObject(quad) // will block until closed

// These objects will not be updated/drawn on each tick
myObj := SomeObject()
win.InitObject(myObj) // will block until initialized
myObj2 := SomeObject()
win.InitObjectAsync(myObj2) // will not block

// When it's time to close:
win.CloseObject(myObj) 
win.CloseObjectAsync(myObj2)

Services are special objects that implement the Service interface, which includes the Object interface, and are also added to Window instances for life-cycle management. The main difference between services and objects is that the former are always initialized/updated before the latter. Objects and services are processed in separate queues, in LIFO order (so technically they're treated as "stacks"), with services always processed before objects. This is particularly important as it relates to asset loading and usage, as described in the next section.

Assets

Types that implement the Asset interface are similar to objects in that they usually need to be initialized and closed, but not updated/drawn on each tick. Additionally, they need to be initialized before the objects that depend on them are initialized. To facilitate this, the AssetLibrary service exists, which ensures the assets it manages are initialized and closed properly. Examples of assets are textures, fonts, and shaders.

By default, the Window type will include an instance of the AssetLibrary service that you can access via the Assets function. Note that you will likely need to use type-assertion before manipulating an asset or using it as an argument to a function expecting a particular type of asset, etc:

// Optimistic retrieval
myShader := win.Assets().Get("my_shader").(Shader)
myShader.Activate() // example usage

// Safe retrieval
if asset := win.Assets().Get("my_shader"); asset != nil {
    if myShader, ok := asset.(Shader); ok {
        myMaterial.AttachShader(myShader) // example usage
    }
}

Of course, you can create more instances of the AssetLibrary service to manage your assets, perhaps assigning one for each stage/scene. Just remember to add the service to the window!

Shape2D

For two-dimensional shapes, the Shape2D type and its associated "New-" functions can be used. These functions simply return Shape2D instances that have had their "Sides" and "Thickness" properties configured accordingly.

For example, gfx.NewQuad() will return a Shape2D that has four sides and no thickness, meaning that its color or texture will fill the entirety of the shape. On the other hand, gfx.NewSquare(.2) will return a Shape2D that also has four sides but with a line thickness set to 20%, resulting in a square line / frame-like shape. For polygons with more sides than a quadrangle, you will need to call gfx.NewShape2D() and set the desired number of sides via the SetSides function. For circles and dots (filled-in circles), you can either do the same with a value of your choosing or you can call the gfx.NewCircle/gfx.NewDot functions, which use a value of 90.

As alluded to, Shape2D instances can be colored, textured, or even both (to tint the texture). You can also enable a blur effect with a variable intensity. Finally, composite shapes can be created simply by adding other Shape2D instances as children (as this type implements WindowObject).

Bringing it all together with a simple example, here we create a stop sign using two Shape2D instances and one Label instance for the sign's verbiage:

stopSign := gfx.NewShape2D()
stopSign.
    SetSides(8).  // of course we need an octagon
    SetThickness(.1).  // this shape is just for the outer white line
    SetColor(gfx.White).  // the default color is white, so this isn't necessary
    SetScale(mgl32.Vec3{.7, .7}).  // it will be 70% of the window size
    SetRotationZ(mgl32.DegToRad(22.5))  // the rotation needs to be adjusted for a stop sign

stopSignFill := gfx.NewShape2D()
stopSignFill.
    SetSides(8).  // the inner fill shape will also be an octagon
    SetColor(gfx.Red).  // red fill, of course
    SetScale(mgl32.Vec3{.9, .9})  // set to 90% the size of parent to not overlap with the line

stopSignText := gfx.NewLabel()
stopSignText.
    SetText("STOP").
    SetFontSize(.3).  // text height will be 30% the size of parent (or window if no parent)
    SetRotationZ(mgl32.DegToRad(-22.5))  // must negate the rotation imposed by parent

// We add the fill/text objects as children, that way we can just deal with one
// object and the children can inherit properties like position, scale, etc, from
// the parent, simplifying the initial configuration and future transformations.
stopSign.AddChildren(stopSignFill, stopSignText)

// From the window's perspective, there is just the one object to manage
win.AddObjects(stopSign)

That should produce this result:
stop_sign

To learn more about what's possible with Shape2D, please see the included examples.

Shape3D

For three-dimensional shapes, there is the Shape3D type and its associated "New-" function. Unlike with Shape2D, you are on the hook to provide the geometry (vertex data), which is done by passing an object that implements the Model interface to the SetModel function.

A Model represents a collection of Mesh instances; a Mesh represents a collection of Face instances; and a Face defines which vertices and associated attributes should be used to render that particular polygon, as well as which Material to use when shading. Faces can be defined using 3 or 4 vertices and reference vertex positions, normals, texture coordinates, etc, by way of indexing...just like the Wavefront OBJ format, which these interfaces were modeled after. In fact, the obj package (found in this module) contains an implementation of these interfaces that you can use to easily import OBJ (Object) and MTL (Material Library) files. Model and Material are also examples of assets, as they include the Asset interface in their definition, and are meant to be shared across Shape3D instances.

Unless your model's vertex position data is already in the normalized, device/screen space, you will also need to supply a Camera to the SetCamera function. Camera is yet another interface but an implementation is at your disposal and can be created by calling gfx.NewCamera(). As with most frameworks, this object is used to apply its view-projection matrix to the world matrix of all objects it's assigned to, ensuring they're all rendered from the same perspective and to of course transform the model's vertices from local to device/screen space.

Finally, you will want to provide a suitable, shader-bindable object to set the model's lighting properties in the shader. If you are using a shader that does not take lights into account, such as the gfx.Shape3DNoLightsShader shader, then you can skip this step. Otherwise, you would pass in this object to the SetLighting function. For example, the gfx.Shape3DShader shader supports up to four directional lights, which can be configured using an instance of QuadDirectionalLighting. More information on shader-bindable objects is included in the Advanced Usage section.

Complete examples for both creating a Model in memory and loading from an OBJ file are included, but here is a shortened example of the latter:

model := obj.NewModel("my_model", "my_model.obj")
model.ComputeTangents(true)
win.Assets().Add(model)

camera := gfx.NewCamera()
// ...set properties
win.AddObject(camera)

lighting := gfx.NewQuadDirectionalLighting()
// ...set properties

myShape := gfx.NewShape3D()
myShape.
    SetModel(model).
    SetCamera(camera).
    SetLighting(lighting)

win.AddObjects(myShape)
Labels & Fonts

Text rendering is handled by the Label type, which is able to render TrueType fonts (thanks to the awesome freetype library). The Label type will use the Roboto font by default, otherwise it will use the one provided to the SetFont function, which expects an object that implements the Font interface. The TrueTypeFont type is one such implementation, encapsulating the functions of the freetype library (truetype package) used to load TTF files into memory. As an Asset, Font instances should be added to an AssetLibrary for life-cycle management.

Example using a provided TrueType font:

coolFont := gfx.NewFont("cool_font", "cool.ttf")
win.Assets().Add(coolFont)
	
// One method for positioning in the bottom-right corner, which
// requires that we shorten the horizontal scale of the label
// from 1.0 (the entire width of the parent or window) to
// something that tightly contains the text, given the font
// size. Note that the horizontal scaling does not affect
// the width or stretching of the text itself, but rather can
// be thought of as the size of the label's container or frame.
hello := gfx.NewLabel()
hello.
    SetText("hello!").
    SetFont(coolFont).
    SetFontSize(.1).
    SetAnchor(gfx.BottomRight).
    SetColor(gfx.Green).
    SetScaleX(.25)

win.AddObjects(hello)

More example Label usage can be found in the included examples and tests.

UI Controls

In addition to labels for text rendering, this library comes with several common (and not so common) user interface controls:

Type Short Description
Button Can be clicked or depressed to trigger further action.
Slider Draggable button on a rail, used to represent a value within a range.
CheckButton (aka, checkbox) Can be clicked to toggle a binary "checked" state.
RadioButton Like CheckButton, but meant to be used in a group where only one can be checked at any given time.
Canvas Used with an implementation of Brush, allows end-users the ability to paint.
SignalLine Used to render a sample stream in real-time, in the form of a line graph.
SignalGroup Used to render multiple, related signal lines.
SignalInspector Used to display the signal value at the position of the mouse cursor as well as aggregated metrics.
FpsCounter Used to display the effective "tick" rate of an object (a close approximation of the framerate).

Example usage of these controls can be found in both the included examples and tests.


Advanced Usage

User-defined Types

The aim of this library is to provide the simplest API possible, without being restrictive or limited. To that end, interfaces are employed extensively and implementing them usually begins with embedding the associated "-Base" type.

For example, you don't need to create a new type to load a custom shader program if it's just comprised of a vertex, fragment, and (optionally) a geometry shader. That's because the BasicShader type, which implements Shader, can handle the compilation/linking of those specific types of shaders. If, however, you needed to incorporate tessellation or wanted to utilize a compute shader, then you would need to create your own implementation of Shader and that would likely begin with creating a type that embeds ShaderBase:

type ComputeShader struct {
    gfx.ShaderBase
}

This is done so that you only need to implement/override what is relevant to the custom behavior of your new type, but of course it's completely optional.

In the case of a tessellation-capable shader, perhaps it would make more sense to embed BasicShader, add members for the tessellation shader sources, and then override Init() to handle the loading, compilation, and linking of the shaders:

type TessellationShader struct {
    gfx.BasicShader // defines the other shader sources for us

    tcSource any // control shader source
    teSource any // evaluation shader source
}

func (s *TessellationShader) Init() (ok bool) {
    // Load/compile/link... binding
}

As another example, we'll compare two different ways we can go about automating the rotation of a Shape2D, which illustrates an important aspect of this type's design and that of many others.

The most direct way is to simply call the SetRotationZ function at some interval on a worker routine:

triangle := gfx.NewShape2D()
win.AddObjects(triangle)

ctx, cancelFunc := context.WithCancel(context.Background())

go func(w *gfx.Window, c context.Context) {
    <-w.ReadyChan()
    angleStep := 0
    speed := float32(.025)
    // We attempt to update the rotation at the same frequency the shape 
    // is rendered on the screen; doing it slower will increase "choppiness" 
    // while faster would mean more contention on the shape's state mutex.
    sleepTimeMilli := 1000 / gfx.TargetFramerate()
    for {
        select {
        case <-ctx.Done():
            return
        default:
        }
    
        angleStep++
        triangle.SetRotationZ(float32(angleStep) * speed)
        time.Sleep(time.Duration(sleepTimeMilli) * time.Millisecond)
    }
}(win, ctx)

As noted in the comments, calling SetRotationZ will result in locking the shape's state mutex, which is also locked on each Draw invocation. That's just one aspect of this approach that is undesirable, with the other being that it relies on sleeping to achieve the ideal update frequency, given the desire to minimize contention on the mutex while aiming for the smoothest possible rotation. Sleeping can be imprecise or inconsistent, which can result in choppiness. Finally, while this approach might be fine in some applications, it certainly isn't very scalable...both from a coding and resource perspective.

The other approach is to create a new type that either wraps or embeds Shape2D:

type SpinningShape2D struct {
    gfx.Shape2D // choosing the embedded approach here
    angleStep int
    speed float32
}

func (s *SpinningShape2D) Update(deltaTime int64) (ok bool) {
    if !s.Shape2D.Update(deltaTime) { // only update if enabled/initialized
        return false
    }

    s.angleStep++
    s.SetRotationZ(float32(s.angleStep) * s.speed)
    return true
}

// Not thread-safe! 
func (s *SpinningShape2D) SetSpinSpeed(speed float32) *SpinningShape2D {
    s.speed = speed // use a mutex or atomic type if expecting changes while drawing
    return s
}

func NewSpinningShape2D() *SpinningShape2D {
    return &SpinningShape2D{
        Shape2D: *gfx.NewShape2D(), // get good defaults
    }
}

Then, inside main():

triangle := NewSpinningShape2D()
triangle.SetSpinSpeed(.01)
win.AddObjects(triangle)

What's clear from the second approach is that it takes more "setup" code, creating the new type in advance, but once it comes time to use the type it's far more concise (as one would expect when using an object that encapsulates the work). Additionally, if you visually compare the two approaches while running the code, and you have a keen eye, you can see the slight choppiness with the first one in some cases while it's not observed with the second. This is because there is no contention on the shape's state mutex and sleeping isn't involved.

Shader Data Binding

When you need to create a new implementation of Material or a new lighting object, you will then have to work with shader-bindable structs, which are essentially used to send data from RAM to VRAM for use by your shaders. These are structs that contain exported members that are of one of the supported bindable types, each mapping to a particular GLSL type. Additionally, these struct members are given the same name (including casing) as the variables/buffers they map to in the shader, sans the required u_ prefix given to the names of shader uniform variables; without the prefix, uniform variable binding will not occur. Note that it's perfectly fine for such structs to include non-bindable members.

Supported bindable types and their associated GLSL types:

Go Type(s) GLSL Type
float32 float
int32 int
uint32 uint
mgl32.Mat4, f32.Mat4, [16]float32 mat4
mgl32.Mat3, f32.Mat3, [9]float32 mat3
mgl32.Vec4, f32.Vec4, [4]float32 vec4
mgl32.Vec3, f32.Vec3, [3]float32 vec3
mgl32.Vec2, f32.Vec2, [2]float32 vec2
SomeStruct, SomeInterfaceNotTexture struct
[]SomeStruct []struct
*SomeStruct uniform buffer object (std140 layout)
gfx.Texture sampler2D

For example, consider a shader with the following uniform defined:

uniform float u_SomeFactor;

To bind a field to that uniform, it would need to be defined like this in the binding struct:

type MyMaterial struct {
    gfx.MaterialBase
    SomeFactor float32
}

And if you'd like to bind to this sampler2D:

uniform sampler2D u_SomeMap;

...then you would do this:

type MyMaterial struct {
    gfx.MaterialBase
    SomeMap gfx.Texture 
}

For uniform buffer objects, a special exception exists... but first, the rule. For this UBO:

layout (std140) uniform MyMaterial { // this is the name that matters
    vec4 SomeProp1;
    vec4 SomeProp2;
} u_Material; // the instance name is optional and can be anything

...you can, of course, do this:

type MyMaterial struct {
    gfx.MaterialBase
    SomeMap gfx.Texture 
    MyMaterial *MyMaterialProperties 
}

type MyMaterialProperties struct { // must have the std140 layout
    SomeProp1 mgl32.Vec4
    SomeProp2 [4]float32 // either of these types will work
}

That would work, since the name of the struct's bindable field matches the name given to the UBO in the shader, however the naming convention doesn't make for a good API-consuming experience, as it will feel redundant and perhaps confusing to work with a field member that has the same name as the containing type. To avoid this circumstance, an exception exists whereby if the field name is Properties it will attempt to map to a UBO with the same name as the containing type:

type MyMaterial struct {
    gfx.MaterialBase
    SomeMap gfx.Texture 
    Properties *MyMaterialProperties 
}

...will now bind to the UBO with the name MyMaterial and consumers should more confident about its usage.

A final note about shader-bindable structs: they may implement sync.Locker, in which case it's recommended to call Lock() on the object before making any changes, then of course Unlock() once finished. That will ensure changes are not made while currently sending the data to VRAM.

For more examples, check out the implementation of Material found in the obj package (obj.BasicMaterial); gfx.BasicCamera for an implementation of Camera; and gfx.QuadDirectionalLighting for an example of a "purely" shader-bindable struct, not pulling double-duty as an Asset or Object, etc.


Screenshots

signals

inspector

filters

radio

label

square

dot

arc

pacman

canvas

cube

shading

Documentation

Overview

Package gfx is a 2D/3D graphics library powered by OpenGL. Easily render shapes, text, and UI controls, including a performant line graph designed for real-time signal analysis.

Index

Constants

View Source
const (
	DefaultFont = "_font_default"
	SquareFont  = "_font_square"
	AnitaFont   = "_font_anita"
)
View Source
const (
	// SignalShader Used by SignalLine to render the line itself, incorporating
	// a geometry shader for line thickness.
	SignalShader = "_shader_signal"

	// BlurXShader Used by Shape2D when blur is enabled to render the horizontally
	// blurred shape.
	BlurXShader = "_shader_blur_x"

	// BlurYShader Used by Shape2D when blur is enabled to render the vertically
	// blurred shape.
	BlurYShader = "_shader_blur_y"

	// TextureShader Used by Shape2D when blur is enabled to render the final,
	// horizontally/vertically blurred shape, but can also be used to render any
	// texture using normalized device/screen coordinates for the vertex data.
	TextureShader = "_shader_texture"

	// Shape2DShader Used by Shape2D to render a textured, two-dimensional
	// shape.
	Shape2DShader = "_shader_shape2d"

	// Shape2DNoTextureShader Used by Shape2D to render a single-colored,
	// two-dimensional shape.
	Shape2DNoTextureShader = "_shader_shape2d_no_texture"

	// Shape3DShader Can be used by Shape3D to render a textured Model with
	// support for: ambient/diffuse/specular/emissive/transparent lighting,
	// directional lights, and diffuse/normal/specular maps.  Expects the Model
	// vertex buffer to have the PositionNormalUvTangentsVaoLayout.
	Shape3DShader = "_shader_shape3d"

	// Shape3DNoNormalSpecularMapsShader Can be used by Shape3D to render a
	// textured Model with support for: ambient/diffuse/specular/emissive/transparent
	// lighting, directional lights, and diffuse maps.  Expects the Model vertex
	// buffer to have the PositionNormalUvVaoLayout.
	Shape3DNoNormalSpecularMapsShader = "_shader_shape3d_no_norm_spec"

	// Shape3DNoLightsShader Can be used by Shape3D to render a
	// textured Model with support for: diffuse/emissive/transparent
	// lighting and diffuse maps.  Expects the Model vertex buffer to have
	// the PositionUvVaoLayout.
	Shape3DNoLightsShader = "_shader_shape3d_no_lights"
)

Variables

View Source
var (
	Transparent             = color.RGBA{}
	White                   = color.RGBA{R: 255, G: 255, B: 255, A: 255}
	Black                   = color.RGBA{A: 255}
	LightGray               = color.RGBA{R: 191, G: 191, B: 191, A: 255}
	Gray                    = color.RGBA{R: 127, G: 127, B: 127, A: 255}
	DarkGray                = color.RGBA{R: 63, G: 63, B: 63, A: 255}
	Red                     = color.RGBA{R: 255, A: 255}
	Green                   = color.RGBA{G: 255, A: 255}
	Blue                    = color.RGBA{B: 255, A: 255}
	Magenta                 = color.RGBA{R: 255, B: 255, A: 255}
	Yellow                  = color.RGBA{R: 255, G: 255, A: 255}
	Purple                  = color.RGBA{R: 100, G: 50, B: 130, A: 255}
	Orange                  = color.RGBA{R: 230, G: 126, B: 34, A: 255}
	Teal                    = color.RGBA{R: 118, G: 215, B: 196, A: 255}
	Maroon                  = color.RGBA{R: 146, G: 43, B: 33, A: 255}
	SkyBlue                 = color.RGBA{R: 174, G: 170, B: 241, A: 255}
	Brown                   = color.RGBA{R: 101, G: 67, B: 33, A: 255}
	DefaultNormalMapColor   = color.RGBA{R: 127, G: 127, B: 255, A: 255}
	DefaultSpecularMapColor = color.RGBA{R: 127, G: 127, B: 127, A: 255}
)
View Source
var (
	DefaultColors = []color.RGBA{
		Red,
		Green,
		Blue,
		Magenta,
		Yellow,
		Purple,
		Orange,
		Teal,
		Maroon,
		SkyBlue,
	}
)

Functions

func Close

func Close()

Close Destroy any remaining windows and release any remaining resources allocated on the graphics card (VRAM). After closing, you must again call Init() if you need to reuse the package. Can call from any routine but should only be called after initializing via Init().

func CloseWindowAsync

func CloseWindowAsync(window GlfwWindow)

CloseWindowAsync Asynchronously stop updating/rendering and close the specified window, releasing any resources it consumed while in use (such as services, objects, and assets). Removing the primary window will also stop the main processing loop by canceling the context that was passed to the Run() function. Can call at any time and from any routine.

func Darken

func Darken(rgba color.RGBA, pct float64) color.RGBA

func ExportSignalDataToCsv

func ExportSignalDataToCsv(line *SignalLine, filenameTemplate ...string) error

func ExportSignalGroupDataToCsv

func ExportSignalGroupDataToCsv(group *SignalGroup, filenameTemplate ...string) error

func FloatArrayToRgba

func FloatArrayToRgba(array [4]float32) color.RGBA

func Init

func Init() error

Init Initialize the gfx package (and GLFW), which must be done before calling Run(). Must call from the main routine.

func InitWindowAsync

func InitWindowAsync(window GlfwWindow)

InitWindowAsync Asynchronously initialize a window to ensure it gets updated/rendered during the main processing loop. Can call at any time and from any routine.

func Lighten

func Lighten(rgba color.RGBA, pct float64) color.RGBA

func Opacity

func Opacity(rgba color.RGBA, pct float64) color.RGBA

func RgbaToFloatArray

func RgbaToFloatArray(rgba color.RGBA) [4]float32

func Run

func Run(ctx context.Context, cancelFunc context.CancelFunc)

Run Start the main processing loop, which will call Update() on all windows at an interval based on the target framerate but limited by system performance. Must call from the main routine.

func SetTargetFramerate

func SetTargetFramerate(framesPerSec uint32)

SetTargetFramerate changes the current target framerate, which must be done before a Window has been initialized.

func SetVSyncEnabled

func SetVSyncEnabled(enabled bool)

SetVSyncEnabled is used to enable/disable V-Sync, which must be done before a Window has been initialized.

func TargetFramerate

func TargetFramerate() (framesPerSec uint32)

TargetFramerate returns the target framerate in frames per second. The actual, rendered framerate will not exceed the monitor's refresh rate when V-Sync is enabled and will always be limited by system performance.

func VSyncEnabled

func VSyncEnabled() (enabled bool)

VSyncEnabled returns true if V-Sync has been enabled. V-Sync ensures the active framebuffer will not be written to while being read by the monitor, which prevents "screen-tearing," but limits the maximum framerate to that of the monitor's refresh rate.

Types

type Anchor

type Anchor int

Anchor specifies how the object should be positioned with respect to its parent, or the window if it has none. Note that when an anchor is used, the Position property of objects is ignored and Margin should be used instead for offset adjustments.

const (
	NoAnchor Anchor = iota
	TopLeft
	MiddleLeft
	BottomLeft
	TopCenter
	Center
	BottomCenter
	TopRight
	MiddleRight
	BottomRight
)

type Asset

type Asset interface {
	Initer
	Closer

	// Initialized shall return true if Init() has already been called.
	Initialized() bool

	// Name shall return the unique name/id given to the asset.
	Name() string

	// Source shall return whatever was used to construct the asset or
	// what otherwise represents the asset itself.  For example, with a
	// Texture asset the source could be the raw binary for a PNG file,
	// which would also be the case when loading the PNG file as an
	// asset itself for other purposes, etc.
	Source() any

	// SourceLibrary shall return the library this asset can use
	// to look for a source that is needed for construction.
	SourceLibrary() *AssetLibrary
	SetSourceLibrary(*AssetLibrary) Asset

	// Protected shall return true if this asset has been marked
	// for protection from closure/removal while being managed
	// by an AssetLibrary. It is used, for example, to allow
	// consumers to freely call DisposeAll() on the Window's
	// default AssetLibrary without concern that it will affect
	// the default assets added therein.
	Protected() bool
	SetProtected(bool) Asset
}

Asset Resources that are needed/shared by objects, have a separate lifecycle than objects, and that are initialized before objects, are considered to be assets. These include resources like fonts, shaders, textures, materials, and models. It's recommended to use an AssetLibrary to manage a collection of related assets to facilitate life-cycle management.

type AssetBase

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

func NewAssetBase

func NewAssetBase(name string, source any) *AssetBase

func (*AssetBase) Close

func (a *AssetBase) Close()

func (*AssetBase) Init

func (a *AssetBase) Init() bool

func (*AssetBase) Initialized

func (a *AssetBase) Initialized() bool

func (*AssetBase) Name

func (a *AssetBase) Name() string

func (*AssetBase) Protected

func (a *AssetBase) Protected() bool

func (*AssetBase) SetProtected

func (a *AssetBase) SetProtected(protected bool) Asset

func (*AssetBase) SetSourceLibrary

func (a *AssetBase) SetSourceLibrary(library *AssetLibrary) Asset

func (*AssetBase) Source

func (a *AssetBase) Source() any

func (*AssetBase) SourceLibrary

func (a *AssetBase) SourceLibrary() *AssetLibrary

type AssetLibrary

type AssetLibrary struct {
	ServiceBase
	// contains filtered or unexported fields
}

func DefaultAssetLibrary

func DefaultAssetLibrary() *AssetLibrary

func NewAssetLibrary

func NewAssetLibrary() *AssetLibrary

func (*AssetLibrary) Add

func (l *AssetLibrary) Add(asset Asset) *AssetLibrary

func (*AssetLibrary) AddEmbeddedFile

func (l *AssetLibrary) AddEmbeddedFile(name string, fs embed.FS) *AssetLibrary

func (*AssetLibrary) AddEmbeddedFiles

func (l *AssetLibrary) AddEmbeddedFiles(fs embed.FS) *AssetLibrary

func (*AssetLibrary) Close

func (l *AssetLibrary) Close()

func (*AssetLibrary) Dispose

func (l *AssetLibrary) Dispose(name string) *AssetLibrary

func (*AssetLibrary) DisposeAll

func (l *AssetLibrary) DisposeAll() *AssetLibrary

func (*AssetLibrary) Get

func (l *AssetLibrary) Get(name string) Asset

func (*AssetLibrary) GetFileReader

func (l *AssetLibrary) GetFileReader(name string) (reader *bufio.Reader, closeFunc func())

func (*AssetLibrary) Init

func (l *AssetLibrary) Init() bool

func (*AssetLibrary) Remove

func (l *AssetLibrary) Remove(name string) *AssetLibrary

func (*AssetLibrary) RemoveAll

func (l *AssetLibrary) RemoveAll() *AssetLibrary

func (*AssetLibrary) Update

func (l *AssetLibrary) Update(_ int64) bool

type BandPassFilter

type BandPassFilter struct {
	FilterBase
}

func NewBandPassFilter

func NewBandPassFilter() *BandPassFilter

func (*BandPassFilter) GenerateCoefficients

func (f *BandPassFilter) GenerateCoefficients(coefficientCount int, sampleRate float64, cutoffFrequencies ...float64) []float64

type BasicBrush

type BasicBrush struct {
	WindowObjectBase
	// contains filtered or unexported fields
}

func NewBasicBrush

func NewBasicBrush() *BasicBrush

func (*BasicBrush) BrushHead

func (b *BasicBrush) BrushHead() (brushHead BrushHeadType)

func (*BasicBrush) Canvas

func (b *BasicBrush) Canvas() (canvas *Canvas)

func (*BasicBrush) OverrideUpdateCanvas

func (b *BasicBrush) OverrideUpdateCanvas(updateFunc func(ms *MouseState))

OverrideUpdateCanvas Structs embedding this type can use this function to provide custom behavior, without having to override Update() or otherwise re-implement its logic. Not thread-safe, so call this during initialization/instantiation.

func (*BasicBrush) SetBrushHead

func (b *BasicBrush) SetBrushHead(brushHead BrushHeadType) *BasicBrush

func (*BasicBrush) SetCanvas

func (b *BasicBrush) SetCanvas(canvas *Canvas) Brush

func (*BasicBrush) SetSize

func (b *BasicBrush) SetSize(size float32) *BasicBrush

func (*BasicBrush) Size

func (b *BasicBrush) Size() (size float32)

func (*BasicBrush) Undo

func (b *BasicBrush) Undo()

func (*BasicBrush) Update

func (b *BasicBrush) Update(deltaTime int64) (ok bool)

type BasicCamera

type BasicCamera struct {
	CameraBase

	Properties *BasicCameraProperties
	// contains filtered or unexported fields
}

func NewCamera

func NewCamera() *BasicCamera

func (*BasicCamera) Location

func (c *BasicCamera) Location() (loc mgl32.Vec4)

func (*BasicCamera) Projection

func (c *BasicCamera) Projection() (proj mgl32.Mat4)

func (*BasicCamera) Resize

func (c *BasicCamera) Resize(_, _, newWidth, newHeight int32)

func (*BasicCamera) SetProjection

func (c *BasicCamera) SetProjection(verticalFoV, aspectRatio, near, far float32) mgl32.Mat4

func (*BasicCamera) Update

func (c *BasicCamera) Update(_ int64) (ok bool)

func (*BasicCamera) View

func (c *BasicCamera) View() (view mgl32.Mat4)

func (*BasicCamera) ViewProjection

func (c *BasicCamera) ViewProjection() (viewProj mgl32.Mat4)

type BasicCameraProperties

type BasicCameraProperties struct {
	Position    mgl32.Vec4
	Target      mgl32.Vec4
	Up          mgl32.Vec4
	ViewProjMat mgl32.Mat4
}

type BasicShader

type BasicShader struct {
	ShaderBase
	// contains filtered or unexported fields
}

func NewBasicShader

func NewBasicShader[T ShaderSource](name string, vertexShaderSource, fragmentShaderSource T, geometryShaderSource ...T) *BasicShader

func (*BasicShader) Close

func (s *BasicShader) Close()

func (*BasicShader) Init

func (s *BasicShader) Init() (ok bool)

type BinaryAsset

type BinaryAsset struct {
	AssetBase
}

func NewBinaryAsset

func NewBinaryAsset(name string, data []byte) *BinaryAsset

type BoundingBox

type BoundingBox struct {
	BoundingObjectBase
}

func NewBoundingBox

func NewBoundingBox() *BoundingBox

func (*BoundingBox) Update

func (b *BoundingBox) Update(_ int64) bool

type BoundingObject

type BoundingObject interface {
	WindowObject

	OnMouseEnter(func(WindowObject, *MouseState))
	OnMouseLeave(func(WindowObject, *MouseState))
	OnPMouseDown(func(WindowObject, *MouseState))
	OnSMouseDown(func(WindowObject, *MouseState))
	OnPMouseUp(func(WindowObject, *MouseState))
	OnSMouseUp(func(WindowObject, *MouseState))
	OnPMouseDepressed(func(WindowObject, *MouseState))
	OnSMouseDepressed(func(WindowObject, *MouseState))
	OnPMouseClick(func(WindowObject, *MouseState))
	OnSMouseClick(func(WindowObject, *MouseState))

	MouseSurface() MouseSurface
	SetMouseSurface(MouseSurface)

	LocalMouse() *MouseState
	MouseOver() bool
}

type BoundingObjectBase

type BoundingObjectBase struct {
	WindowObjectBase
	// contains filtered or unexported fields
}

func NewBoundingObject

func NewBoundingObject() *BoundingObjectBase

func (*BoundingObjectBase) Init

func (o *BoundingObjectBase) Init() bool

func (*BoundingObjectBase) LocalMouse

func (o *BoundingObjectBase) LocalMouse() *MouseState

func (*BoundingObjectBase) MouseOver

func (o *BoundingObjectBase) MouseOver() bool

func (*BoundingObjectBase) MouseSurface

func (o *BoundingObjectBase) MouseSurface() MouseSurface

func (*BoundingObjectBase) OnMouseEnter

func (o *BoundingObjectBase) OnMouseEnter(handler func(sender WindowObject, mouseState *MouseState))

func (*BoundingObjectBase) OnMouseLeave

func (o *BoundingObjectBase) OnMouseLeave(handler func(sender WindowObject, mouseState *MouseState))

func (*BoundingObjectBase) OnPMouseClick

func (o *BoundingObjectBase) OnPMouseClick(handler func(sender WindowObject, mouseState *MouseState))

func (*BoundingObjectBase) OnPMouseDepressed

func (o *BoundingObjectBase) OnPMouseDepressed(handler func(sender WindowObject, mouseState *MouseState))

func (*BoundingObjectBase) OnPMouseDown

func (o *BoundingObjectBase) OnPMouseDown(handler func(sender WindowObject, mouseState *MouseState))

func (*BoundingObjectBase) OnPMouseUp

func (o *BoundingObjectBase) OnPMouseUp(handler func(sender WindowObject, mouseState *MouseState))

func (*BoundingObjectBase) OnSMouseClick

func (o *BoundingObjectBase) OnSMouseClick(handler func(sender WindowObject, mouseState *MouseState))

func (*BoundingObjectBase) OnSMouseDepressed

func (o *BoundingObjectBase) OnSMouseDepressed(handler func(sender WindowObject, mouseState *MouseState))

func (*BoundingObjectBase) OnSMouseDown

func (o *BoundingObjectBase) OnSMouseDown(handler func(sender WindowObject, mouseState *MouseState))

func (*BoundingObjectBase) OnSMouseUp

func (o *BoundingObjectBase) OnSMouseUp(handler func(sender WindowObject, mouseState *MouseState))

func (*BoundingObjectBase) SetMouseSurface

func (o *BoundingObjectBase) SetMouseSurface(surface MouseSurface)

type BoundingRadius

type BoundingRadius struct {
	BoundingObjectBase
}

func NewBoundingRadius

func NewBoundingRadius() *BoundingRadius

func (*BoundingRadius) Update

func (r *BoundingRadius) Update(_ int64) bool

type Bounds

type Bounds struct {
	Top, Right, Bottom, Left float32
}

Bounds represents the boundaries or "frame" in which the associated object is rendered, if not the full width/height of the window. Objects that become children of other objects will have their bounds adjusted, such that the scale and positioning of the parent determines the maximum bounds for its children, affecting their scaling/positioning/anchoring, etc. Values are in the normalized device/screen space range of [-1,1] for both axes.

type Brush

type Brush interface {
	WindowObject

	// Canvas shall return the canvas to which this brush is assigned.
	Canvas() *Canvas
	SetCanvas(*Canvas) Brush

	// Undo shall revert the last change made to the Canvas.
	Undo()
}

Brush objects are used to paint a Canvas by the end-user by clicking and dragging across the canvas. Brushes should have no effect if not enabled.

type BrushHeadType

type BrushHeadType int
const (
	RoundBrushHead BrushHeadType = iota
	SquareBrushHead
)

type Button

type Button struct {
	View
	// contains filtered or unexported fields
}

func NewButton

func NewButton(circular ...bool) *Button

func (*Button) Close

func (b *Button) Close()

func (*Button) Draw

func (b *Button) Draw(deltaTime int64) (ok bool)

func (*Button) Init

func (b *Button) Init() (ok bool)

func (*Button) Label

func (b *Button) Label() *Label

func (*Button) OnClick

func (b *Button) OnClick(handler func(sender WindowObject, mouseState *MouseState)) *Button

func (*Button) OnDepressed

func (b *Button) OnDepressed(handler func(sender WindowObject, mouseState *MouseState)) *Button

func (*Button) Resize

func (b *Button) Resize(newWidth, newHeight int)

func (*Button) SetDisabledBorderColor

func (b *Button) SetDisabledBorderColor(rgba color.RGBA) *Button

func (*Button) SetDisabledFillColor

func (b *Button) SetDisabledFillColor(rgba color.RGBA) *Button

func (*Button) SetDisabledTextColor

func (b *Button) SetDisabledTextColor(rgba color.RGBA) *Button

func (*Button) SetEnabled

func (b *Button) SetEnabled(enabled bool) Object

func (*Button) SetFontSize

func (b *Button) SetFontSize(size float32) *Button

func (*Button) SetMaintainAspectRatio

func (b *Button) SetMaintainAspectRatio(maintainAspectRatio bool) WindowObject

func (*Button) SetMouseDownBorderColor

func (b *Button) SetMouseDownBorderColor(rgba color.RGBA) *Button

func (*Button) SetMouseDownFillColor

func (b *Button) SetMouseDownFillColor(rgba color.RGBA) *Button

func (*Button) SetMouseDownTextColor

func (b *Button) SetMouseDownTextColor(rgba color.RGBA) *Button

func (*Button) SetMouseEnterBorderColor

func (b *Button) SetMouseEnterBorderColor(rgba color.RGBA) *Button

func (*Button) SetMouseEnterFillColor

func (b *Button) SetMouseEnterFillColor(rgba color.RGBA) *Button

func (*Button) SetMouseEnterTextColor

func (b *Button) SetMouseEnterTextColor(rgba color.RGBA) *Button

func (*Button) SetMouseSurface

func (b *Button) SetMouseSurface(surface MouseSurface)

func (*Button) SetParent

func (b *Button) SetParent(parent WindowObject, recursive ...bool) WindowObject

func (*Button) SetText

func (b *Button) SetText(text string) *Button

func (*Button) SetTextColor

func (b *Button) SetTextColor(rgba color.RGBA) *Button

func (*Button) SetWindow

func (b *Button) SetWindow(window *Window) WindowObject

func (*Button) Text

func (b *Button) Text() string

func (*Button) Update

func (b *Button) Update(deltaTime int64) (ok bool)

type Camera

type Camera interface {
	Object
	sync.Locker

	// Location shall return the camera's coordinates in world space,
	// using a 4-byte-aligned float array.
	Location() mgl32.Vec4

	// View shall return the current view matrix for the camera.
	View() mgl32.Mat4

	// Projection shall return the current projection matrix for the camera.
	Projection() mgl32.Mat4

	// ViewProjection shall return the current combined view-projection matrix
	// for the camera.  Passing this matrix to the shader rather than computing
	// it there may increase performance.
	ViewProjection() mgl32.Mat4
}

Camera Use cameras to apply the same view-projection matrix to the world matrix of each Shape3D object to which the camera is assigned, ensuring they are all rendered from the same perspective. Must be added to a window to ensure its properties get updated over time.

type CameraBase

type CameraBase struct {
	ObjectBase
	// contains filtered or unexported fields
}

func (*CameraBase) Lock

func (c *CameraBase) Lock()

func (*CameraBase) Unlock

func (c *CameraBase) Unlock()

type Canvas

type Canvas struct {
	View
	// contains filtered or unexported fields
}

Canvas can be used with a Brush to allow end-users the ability to paint to a Texture2D-based surface, which can then be exported to a PNG. A canvas is just a type of View, which means you can change the background (FillColor) and, optionally, configure a frame (Border) with a specific thickness/color, but that frame will not be part of the exported PNG.

func NewCanvas

func NewCanvas() *Canvas

func (*Canvas) Clear

func (c *Canvas) Clear()

func (*Canvas) Close

func (c *Canvas) Close()

func (*Canvas) Draw

func (c *Canvas) Draw(deltaTime int64) (ok bool)

func (*Canvas) Export

func (c *Canvas) Export(toDirectory ...string)

func (*Canvas) Init

func (c *Canvas) Init() (ok bool)

func (*Canvas) Mouse

func (c *Canvas) Mouse() *MouseState

func (*Canvas) Resize

func (c *Canvas) Resize(newWidth, newHeight int)

func (*Canvas) SetMaintainAspectRatio

func (c *Canvas) SetMaintainAspectRatio(maintainAspectRatio bool) WindowObject

func (*Canvas) SetParent

func (c *Canvas) SetParent(parent WindowObject, recursive ...bool) WindowObject

func (*Canvas) SetWindow

func (c *Canvas) SetWindow(window *Window) WindowObject

func (*Canvas) Surface

func (c *Canvas) Surface() Texture

func (*Canvas) Update

func (c *Canvas) Update(deltaTime int64) (ok bool)

func (*Canvas) UpdateSurface

func (c *Canvas) UpdateSurface(surface Texture)

type CheckButton

type CheckButton struct {
	Button
	// contains filtered or unexported fields
}

func NewCheckBox

func NewCheckBox() *CheckButton

func NewRadioButton

func NewRadioButton() *CheckButton

func (*CheckButton) CheckShape

func (b *CheckButton) CheckShape() *Shape2D

func (*CheckButton) Checked

func (b *CheckButton) Checked() bool

func (*CheckButton) Close

func (b *CheckButton) Close()

func (*CheckButton) Draw

func (b *CheckButton) Draw(deltaTime int64) (ok bool)

func (*CheckButton) Init

func (b *CheckButton) Init() (ok bool)

func (*CheckButton) OnCheckedChanged

func (b *CheckButton) OnCheckedChanged(handler func(sender WindowObject, checked bool)) *CheckButton

func (*CheckButton) OnClick

func (b *CheckButton) OnClick(handler func(sender WindowObject, mouseState *MouseState)) *CheckButton

func (*CheckButton) Resize

func (b *CheckButton) Resize(newWidth, newHeight int)

func (*CheckButton) SetChecked

func (b *CheckButton) SetChecked(checked bool)

func (*CheckButton) SetColor

func (b *CheckButton) SetColor(rgba color.RGBA) WindowObject

func (*CheckButton) SetMaintainAspectRatio

func (b *CheckButton) SetMaintainAspectRatio(maintainAspectRatio bool) WindowObject

func (*CheckButton) SetMouseDownColor

func (b *CheckButton) SetMouseDownColor(rgba color.RGBA) *CheckButton

func (*CheckButton) SetMouseEnterColor

func (b *CheckButton) SetMouseEnterColor(rgba color.RGBA) *CheckButton

func (*CheckButton) SetWindow

func (b *CheckButton) SetWindow(window *Window) WindowObject

func (*CheckButton) Update

func (b *CheckButton) Update(deltaTime int64) (ok bool)

type Closer

type Closer interface {
	Close()
}

type DirectionalLight

type DirectionalLight struct {
	LightBase

	Color     mgl32.Vec3
	Direction mgl32.Vec3
}

func NewDirectionalLight

func NewDirectionalLight() *DirectionalLight

type DrawableObject

type DrawableObject interface {
	Object

	Draw(int64) bool

	Visible() bool
	SetVisibility(bool) DrawableObject
}

type DrawableObjectBase

type DrawableObjectBase struct {
	ObjectBase
	// contains filtered or unexported fields
}

func (*DrawableObjectBase) Draw

func (o *DrawableObjectBase) Draw(_ int64) (ok bool)

func (*DrawableObjectBase) SetVisibility

func (o *DrawableObjectBase) SetVisibility(visible bool) DrawableObject

func (*DrawableObjectBase) Visible

func (o *DrawableObjectBase) Visible() bool

type Face

type Face interface {
	// VertexIndices shall return the indices for vertex positions associated
	// with the face.
	VertexIndices() []int

	// ColorIndices shall return the indices for vertex colors associated
	// with the face.
	ColorIndices() []int

	// UvIndices shall return the indices for vertex texture coordinates
	// associated with the face.
	UvIndices() []int

	// NormalIndices shall return the indices for normal vectors associated
	// with the face.
	NormalIndices() []int

	// TangentIndices shall return the indices for tangent vectors associated
	// with the face.
	TangentIndices() []int

	// BitangentIndices shall return the indices for bitangent vectors associated
	// with the face.
	BitangentIndices() []int

	// AttachedMaterial shall return the Material instance that will be used
	// when shading the face during rendering.
	AttachedMaterial() Material
}

Face instances hold the indices of the vertex attributes that comprise the face. A face may be defined with either 3 or 4 vertices.

type FaceBase

type FaceBase struct{}

func (*FaceBase) AttachedMaterial

func (f *FaceBase) AttachedMaterial() Material

func (*FaceBase) BitangentIndices

func (f *FaceBase) BitangentIndices() []int

func (*FaceBase) ColorIndices

func (f *FaceBase) ColorIndices() []int

func (*FaceBase) NormalIndices

func (f *FaceBase) NormalIndices() []int

func (*FaceBase) TangentIndices

func (f *FaceBase) TangentIndices() []int

func (*FaceBase) UvIndices

func (f *FaceBase) UvIndices() []int

func (*FaceBase) VertexIndices

func (f *FaceBase) VertexIndices() []int

type FastFourierTransformer

type FastFourierTransformer struct {
	TransformerBase
	// contains filtered or unexported fields
}

func NewFastFourierTransformer

func NewFastFourierTransformer(dataSize int, sampleRate float64) *FastFourierTransformer

func (*FastFourierTransformer) SetSampleRate

func (t *FastFourierTransformer) SetSampleRate(rate float64)

func (*FastFourierTransformer) Transform

func (t *FastFourierTransformer) Transform(dst, src []float64) []float64

type Filter

type Filter interface {
	// Name shall return the unique name given to the filter.
	Name() string
	SetName(string)

	// Enabled shall return true if this filter should actually have an
	// effect on the data being passed through it.
	Enabled() bool
	SetEnabled(bool)

	// SampleRate shall return the current sample rate of the filter.
	SampleRate() float64

	// CutoffFrequencies shall return the current cutoff frequencies of
	// the filter.
	CutoffFrequencies() []float64

	// GenerateCoefficients shall generate the coefficients for the filter.
	GenerateCoefficients(int, float64, ...float64) []float64

	// CoefficientCount shall return the current coefficient count.
	CoefficientCount() int

	// Apply shall filter the data, passed to it as a float array along
	// with the index of value to be filtered, and shall return the result.
	Apply(int, []float64) float64
}

Filter instances are used to filter the data being added to signals.

type FilterBase

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

func NewFilterBase

func NewFilterBase(name string) *FilterBase

func (*FilterBase) Apply

func (f *FilterBase) Apply(index int, input []float64) (output float64)

func (*FilterBase) CoefficientCount

func (f *FilterBase) CoefficientCount() int

func (*FilterBase) CutoffFrequencies

func (f *FilterBase) CutoffFrequencies() []float64

func (*FilterBase) Enabled

func (f *FilterBase) Enabled() bool

func (*FilterBase) GenerateCoefficients

func (f *FilterBase) GenerateCoefficients(int, float64, ...float64) []float64

func (*FilterBase) Name

func (f *FilterBase) Name() string

func (*FilterBase) SampleRate

func (f *FilterBase) SampleRate() float64

func (*FilterBase) SetEnabled

func (f *FilterBase) SetEnabled(enabled bool)

func (*FilterBase) SetName

func (f *FilterBase) SetName(name string)

type Font

type Font interface {
	Asset

	// TTF shall return a pointer to the TrueType font that has been loaded
	// into memory and is ready to be used to rasterize text to a texture.
	TTF() *truetype.Font
}

Font represents a TrueType font asset that will be used to render the text of a Label object.

type FontSource

type FontSource interface {
	[]byte | string
}

type FpsCounter

type FpsCounter struct {
	WindowObjectBase
	// contains filtered or unexported fields
}

FpsCounter When added to a Window, will display the current frames per second, calculating the metric at the update interval specified (defaults to 250 ms). Note that this object cannot be disabled or hidden, only added/removed from a Window.

func NewFpsCounter

func NewFpsCounter(updateIntervalMilli ...int) *FpsCounter

func (*FpsCounter) Draw

func (c *FpsCounter) Draw(deltaTime int64) bool

func (*FpsCounter) Init

func (c *FpsCounter) Init() (ok bool)

func (*FpsCounter) Label

func (c *FpsCounter) Label() *Label

func (*FpsCounter) Resize

func (c *FpsCounter) Resize(newWidth, newHeight int)

func (*FpsCounter) SetMaintainAspectRatio

func (c *FpsCounter) SetMaintainAspectRatio(maintainAspectRatio bool) WindowObject

func (*FpsCounter) SetUpdateInterval

func (c *FpsCounter) SetUpdateInterval(milliseconds int) *FpsCounter

func (*FpsCounter) SetWindow

func (c *FpsCounter) SetWindow(window *Window) WindowObject

func (*FpsCounter) Update

func (c *FpsCounter) Update(deltaTime int64) (ok bool)

type GlAsset

type GlAsset interface {
	Asset

	// GlName shall return the unique name/id assigned to the asset by the
	// OpenGL framework.
	GlName() uint32
}

GlAsset assets are those with an associated OpenGL name, which is an unsigned number that is assigned with creating the object (usually one taking up memory in VRAM).

type GlfwWindow

type GlfwWindow interface {
	GLFW() *glfw.Window

	// Title shall return the window's title, which is rendered in the
	// title bar, if the window is decorated (not borderless).
	Title() string

	// Width shall return the window's width, in pixels.
	Width() int

	// Height shall return the window's height, in pixels.
	Height() int

	// Borderless shall return true if the window will not be decorated
	// with a border/frame or a title bar.
	Borderless() bool

	// Resizable shall return true if the window can be resized either
	// by the maximize button or by dragging the edges/corners; both
	// of which are only possible with a decorated window.  Note that
	// you can always change the size of a window programmatically.
	Resizable() bool

	// MultiSamplingEnabled shall return true if antialiasing has been
	// enabled, which is provided by OpenGL's native MSAA capability,
	// with the sample size set to 4.
	MultiSamplingEnabled() bool

	// IsSecondary shall return true if the window has been designated
	// as a secondary/tool/dialog window, which means closing it will
	// not result in the application closing.
	IsSecondary() bool

	// Init should only be called by the engine and shall cause the window
	// to initialize itself, its services/objects, and begin the process of
	// updating ("ticking") them at a rate based on the target framerate.
	// Consumers of this package should initialize windows by passing them
	// to gfx.InitWindowAsync().
	Init(*glfw.Window, context.Context)

	// Update should only be called by the engine and shall cause the window
	// to update its services/objects, passing in the amount of time (in
	// microseconds) that has passed since the last update.
	Update(deltaTime int64)

	// Close should only be called by the engine and shall cause the window
	// to release any resources it consumed and call Close() on its
	// services/objects, causing them to do the same. Consumers of this
	// package should close windows by passing them to gfx.CloseWindowAsync().
	Close()
}

GlfwWindow is a wrapper for a GLFW window that also contains the services, objects, and assets needed to render and manage a scene or user interface, etc. Life-cycle functions Init(), Update(), and Close() should NOT be directly invoked by importers of this package and are only exported so consumers may provide custom GlfwWindow implementations.

type HighPassFilter

type HighPassFilter struct {
	FilterBase
}

func NewHighPassFilter

func NewHighPassFilter() *HighPassFilter

func (*HighPassFilter) GenerateCoefficients

func (f *HighPassFilter) GenerateCoefficients(coefficientCount int, sampleRate float64, cutoffFrequencies ...float64) []float64

type Initer

type Initer interface {
	Init() bool
}

type KeyEvent

type KeyEvent struct {
	Key    glfw.Key
	Action glfw.Action
}

func (*KeyEvent) Event

func (e *KeyEvent) Event() uint64

type KeyEventHandler

type KeyEventHandler struct {
	Receiver any
	Key      glfw.Key
	Action   glfw.Action
	Callback func(*Window, glfw.Key, glfw.Action)
}

func (*KeyEventHandler) Event

func (h *KeyEventHandler) Event() uint64

type Label

type Label struct {
	View
	// contains filtered or unexported fields
}

func NewLabel

func NewLabel() *Label

func (*Label) Alignment

func (l *Label) Alignment() TextAlignment

func (*Label) CacheEnabled

func (l *Label) CacheEnabled() bool

func (*Label) Close

func (l *Label) Close()

func (*Label) Draw

func (l *Label) Draw(deltaTime int64) (ok bool)

func (*Label) Font

func (l *Label) Font() Font

func (*Label) Init

func (l *Label) Init() (ok bool)

func (*Label) RefreshLayout

func (l *Label) RefreshLayout()

func (*Label) Resize

func (l *Label) Resize(newWidth, newHeight int)

func (*Label) SetAlignment

func (l *Label) SetAlignment(alignment TextAlignment) *Label

func (*Label) SetCacheEnabled

func (l *Label) SetCacheEnabled(enabled bool) *Label

func (*Label) SetColor

func (l *Label) SetColor(rgba color.RGBA) WindowObject

func (*Label) SetFillColor

func (l *Label) SetFillColor(rgba color.RGBA) *Label

func (*Label) SetFont

func (l *Label) SetFont(ttfFont Font) *Label

func (*Label) SetFontSize

func (l *Label) SetFontSize(size float32) *Label

func (*Label) SetMaintainAspectRatio

func (l *Label) SetMaintainAspectRatio(maintainAspectRatio bool) WindowObject

func (*Label) SetPaddingBottom

func (l *Label) SetPaddingBottom(padding float32) *Label

func (*Label) SetPaddingLeft

func (l *Label) SetPaddingLeft(padding float32) *Label

func (*Label) SetPaddingRight

func (l *Label) SetPaddingRight(padding float32) *Label

func (*Label) SetPaddingTop

func (l *Label) SetPaddingTop(padding float32) *Label

func (*Label) SetParent

func (l *Label) SetParent(parent WindowObject, recursive ...bool) WindowObject

func (*Label) SetText

func (l *Label) SetText(text string) *Label

func (*Label) SetWindow

func (l *Label) SetWindow(window *Window) WindowObject

func (*Label) Text

func (l *Label) Text() string

func (*Label) Update

func (l *Label) Update(deltaTime int64) (ok bool)

type Light

type Light interface {
	sync.Locker

	// Name shall return the unique name/id given to the light, if one was
	// given.
	Name() string
	SetName(string)

	// Enabled shall return true if the light will contribute to the lighting
	// being applied to the model.
	Enabled() bool
	SetEnabled(bool)
}

Light Lights are used to illuminate models within a scene and are normally part of a shader-bindable object used when setting the Lighting property of Shape3D objects. Before changing a light's properties, it is recommended to call Lock() to ensure the shader is not being sent their values while they are being changed; and of course, call Unlock() when finished changing them.

type LightBase

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

func (*LightBase) Enabled

func (l *LightBase) Enabled() bool

func (*LightBase) Lock

func (l *LightBase) Lock()

func (*LightBase) Name

func (l *LightBase) Name() string

func (*LightBase) SetEnabled

func (l *LightBase) SetEnabled(enabled bool)

func (*LightBase) SetName

func (l *LightBase) SetName(name string)

func (*LightBase) Unlock

func (l *LightBase) Unlock()

type LowPassFilter

type LowPassFilter struct {
	FilterBase
}

func NewLowPassFilter

func NewLowPassFilter() *LowPassFilter

func (*LowPassFilter) GenerateCoefficients

func (f *LowPassFilter) GenerateCoefficients(coefficientCount int, sampleRate float64, cutoffFrequencies ...float64) []float64

type Margin

type Margin struct {
	Top, Right, Bottom, Left float32
}

Margin contains the position offsets used when objects are anchored, in the normalized device/screen space range of [-1,1] for both axes.

type Material

type Material interface {
	Asset
	sync.Locker

	// AttachedShader shall return the shader that this material will bind
	// to, sending it the property values and texture maps that constitute
	// the material.
	AttachedShader() Shader
	AttachShader(shader Shader)
}

Material instances are used in the rendering of faces, providing various properties that will be used by the attached shader. Before these properties are changed, it is recommended to call Lock() on the material to ensure the shader is not being sent their values while they are being changed; and of course, call Unlock() when finished changing them.

type MaterialBase

type MaterialBase struct {
	AssetBase
	// contains filtered or unexported fields
}

func (*MaterialBase) AttachShader

func (m *MaterialBase) AttachShader(shader Shader)

func (*MaterialBase) AttachedShader

func (m *MaterialBase) AttachedShader() Shader

func (*MaterialBase) Lock

func (m *MaterialBase) Lock()

func (*MaterialBase) Unlock

func (m *MaterialBase) Unlock()

type MaterialLibrarySource

type MaterialLibrarySource interface {
	[]byte | string
}

type Mesh

type Mesh interface {
	Transform

	// Name shall return the given name/id of the mesh, which may or may
	// not be unique within the model.
	Name() string

	// Faces shall return an array of Face instances that comprise the mesh.
	Faces() []Face
}

Mesh instances contain the collection of faces that comprise the mesh.

type MeshBase

type MeshBase struct {
	ObjectTransform
}

func (*MeshBase) Name

func (m *MeshBase) Name() string

type Model

type Model interface {
	Asset

	// Vertices shall return a float array containing the positions of the
	// vertices in local/model space.
	Vertices() []float32

	// Colors shall return a float array containing the colors of each
	// vertex.  May optionally return nil for a different vertex attribute
	// layout.
	Colors() []float32

	// UVs shall return a float array containing the texture coordinates
	// of each vertex.  May optionally return nil for a different vertex
	// attribute layout.
	UVs() []float32

	// Normals shall return a float array containing the normal vectors
	// associated with the vertices.  May optionally return nil for a
	// different vertex attribute layout.
	Normals() []float32

	// Tangents shall return a float array containing the tangent
	// vectors associated with the vertices.  May optionally return
	// nil for a different vertex attribute layout.
	Tangents() []float32

	// Bitangents shall return a float array containing the bitangent
	// vectors associated with the vertices.  May optionally return
	// nil for a different vertex attribute layout.
	Bitangents() []float32

	// Meshes shall return an array of Mesh instances that comprise
	// the model.
	Meshes() []Mesh
}

Model instances hold the vertex information used to render a Shape3D object. Changes made to a model asset (after loading it or after it has been initialized, etc) will only affect new Shape3D instances to which it is assigned; i.e., once a Shape3D object has been initialized, it will no longer be influenced by changes to the model asset. For an example implementation, see the obj package.

type ModelBase

type ModelBase struct {
	AssetBase
}

func (*ModelBase) Bitangents

func (m *ModelBase) Bitangents() []float32

func (*ModelBase) Colors

func (m *ModelBase) Colors() []float32

func (*ModelBase) Normals

func (m *ModelBase) Normals() []float32

func (*ModelBase) Tangents

func (m *ModelBase) Tangents() []float32

func (*ModelBase) UVs

func (m *ModelBase) UVs() []float32

func (*ModelBase) Vertices

func (m *ModelBase) Vertices() []float32

type ModelSource

type ModelSource interface {
	[]byte | string
}

type MouseState

type MouseState struct {
	X, Y                       float32
	PrimaryDown, SecondaryDown bool
	ButtonsSwapped             bool
}

func (*MouseState) Update

func (s *MouseState) Update(button glfw.MouseButton, action glfw.Action)

type MouseSurface

type MouseSurface interface {
	Mouse() *MouseState
	Width() int
	Height() int
}
type NavKeys int
const (
	TabAndArrowKeys NavKeys = iota
	TabKeyOnly
	ArrowKeysOnly
)

type Object

type Object interface {
	Initer
	Update(int64) bool
	Closer

	Initialized() bool
	Name() string
	SetName(string) Object

	Tag() any
	SetTag(any) Object

	Enabled() bool
	SetEnabled(bool) Object
}

type ObjectBase

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

func (*ObjectBase) Close

func (o *ObjectBase) Close()

func (*ObjectBase) Enabled

func (o *ObjectBase) Enabled() bool

func (*ObjectBase) Init

func (o *ObjectBase) Init() (ok bool)

func (*ObjectBase) Initialized

func (o *ObjectBase) Initialized() bool

func (*ObjectBase) Name

func (o *ObjectBase) Name() string

func (*ObjectBase) SetEnabled

func (o *ObjectBase) SetEnabled(enabled bool) Object

func (*ObjectBase) SetName

func (o *ObjectBase) SetName(name string) Object

func (*ObjectBase) SetTag

func (o *ObjectBase) SetTag(value any) Object

func (*ObjectBase) Tag

func (o *ObjectBase) Tag() any

func (*ObjectBase) Update

func (o *ObjectBase) Update(_ int64) (ok bool)

type ObjectTransform

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

func NewObjectTransform

func NewObjectTransform() *ObjectTransform

func (*ObjectTransform) Origin

func (t *ObjectTransform) Origin() mgl32.Vec3

func (*ObjectTransform) ParentTransform

func (t *ObjectTransform) ParentTransform() Transform

func (*ObjectTransform) Position

func (t *ObjectTransform) Position() mgl32.Vec3

func (*ObjectTransform) Rotation

func (t *ObjectTransform) Rotation() mgl32.Vec3

func (*ObjectTransform) RotationQuat

func (t *ObjectTransform) RotationQuat() mgl32.Quat

func (*ObjectTransform) Scale

func (t *ObjectTransform) Scale() mgl32.Vec3

func (*ObjectTransform) SetOrigin

func (t *ObjectTransform) SetOrigin(origin mgl32.Vec3) Transform

func (*ObjectTransform) SetParentTransform

func (t *ObjectTransform) SetParentTransform(parent Transform) Transform

func (*ObjectTransform) SetPosition

func (t *ObjectTransform) SetPosition(position mgl32.Vec3) Transform

func (*ObjectTransform) SetPositionX

func (t *ObjectTransform) SetPositionX(x float32) Transform

func (*ObjectTransform) SetPositionY

func (t *ObjectTransform) SetPositionY(y float32) Transform

func (*ObjectTransform) SetPositionZ

func (t *ObjectTransform) SetPositionZ(z float32) Transform

func (*ObjectTransform) SetRotation

func (t *ObjectTransform) SetRotation(rotation mgl32.Vec3) Transform

func (*ObjectTransform) SetRotationQuat

func (t *ObjectTransform) SetRotationQuat(rotation mgl32.Quat) Transform

func (*ObjectTransform) SetRotationX

func (t *ObjectTransform) SetRotationX(x float32) Transform

func (*ObjectTransform) SetRotationY

func (t *ObjectTransform) SetRotationY(y float32) Transform

func (*ObjectTransform) SetRotationZ

func (t *ObjectTransform) SetRotationZ(z float32) Transform

func (*ObjectTransform) SetScale

func (t *ObjectTransform) SetScale(scale mgl32.Vec3) Transform

func (*ObjectTransform) SetScaleX

func (t *ObjectTransform) SetScaleX(x float32) Transform

func (*ObjectTransform) SetScaleY

func (t *ObjectTransform) SetScaleY(y float32) Transform

func (*ObjectTransform) SetScaleZ

func (t *ObjectTransform) SetScaleZ(z float32) Transform

func (*ObjectTransform) WorldMatrix

func (t *ObjectTransform) WorldMatrix() mgl32.Mat4

func (*ObjectTransform) WorldOrigin

func (t *ObjectTransform) WorldOrigin() mgl32.Vec3

func (*ObjectTransform) WorldPosition

func (t *ObjectTransform) WorldPosition() mgl32.Vec3

func (*ObjectTransform) WorldRotation

func (t *ObjectTransform) WorldRotation() mgl32.Vec3

func (*ObjectTransform) WorldScale

func (t *ObjectTransform) WorldScale() mgl32.Vec3

type Orientation

type Orientation int

Orientation specifies how certain controls should be oriented/arranged, such as whether a Slider object's button will slide along a horizontally or vertically aligned rail, etc.

const (
	Horizontal Orientation = iota
	Vertical
)

type QuadDirectionalLighting

type QuadDirectionalLighting struct {
	Lights     [4]DirectionalLight
	LightCount int32
	// contains filtered or unexported fields
}

func NewQuadDirectionalLighting

func NewQuadDirectionalLighting() *QuadDirectionalLighting

func (*QuadDirectionalLighting) Lock

func (l *QuadDirectionalLighting) Lock()

func (*QuadDirectionalLighting) Unlock

func (l *QuadDirectionalLighting) Unlock()

type QualityLevel

type QualityLevel int

QualityLevel is used to determine the visual quality vs performance balance when rendering certain objects, like textures.

const (
	LowestQuality QualityLevel = iota
	VeryLowQuality
	LowQuality
	MediumQuality
	HighQuality
	VeryHighQuality
	HighestQuality
)

type Resizer

type Resizer interface {
	Resize(newWidth, newHeight int)
}

Resizer should be implemented by WindowObject types that need to readjust themselves, recompute variables, etc, whenever the window's size has changed or when going from windowed to fullscreen mode or vice-versa.

type Service

type Service interface {
	Object

	// Window shall return the Window to which this service was assigned.
	Window() *Window
	SetWindow(*Window) Service

	// Protected shall return true if this service has been marked
	// for protection from closure/removal after being added to a
	// Window. It is used, for example, to allow consumers to freely
	// call DisposeAllServices() on the Window without concern that it
	// will affect the default services that a Window comes with.
	Protected() bool
	SetProtected(bool) Service
}

Service objects are initialized/updated before any other type of Object, are meant to have a life cycle that lives beyond the other objects added to a window, and can be used by other objects for various purposes. The AssetLibrary type is an example implementation of Service.

type ServiceBase

type ServiceBase struct {
	ObjectBase
	// contains filtered or unexported fields
}

func (*ServiceBase) Protected

func (s *ServiceBase) Protected() bool

func (*ServiceBase) SetProtected

func (s *ServiceBase) SetProtected(protected bool) Service

func (*ServiceBase) SetWindow

func (s *ServiceBase) SetWindow(window *Window) Service

func (*ServiceBase) Window

func (s *ServiceBase) Window() *Window

type Shader

type Shader interface {
	GlAsset

	// Activate shall change the current OpenGL context, making this shader
	// program the active one.
	Activate()

	// GetAttribLocation shall return the location of the given vertex
	// attribute.  Will return -1 if not found in the shader.
	GetAttribLocation(name string) int32

	// GetUniformLocation shall return the location of the given uniform
	// variable.  Will return -1 if not found in the shader.
	GetUniformLocation(name string) int32

	// GetUniformBlockIndex shall return the location of the given uniform
	// block.  Will return -1 if not found in the shader.
	GetUniformBlockIndex(name string) uint32
}

Shader assets represent compiled shader programs that are then used to render objects on the screen.

type ShaderBase

type ShaderBase struct {
	AssetBase
	// contains filtered or unexported fields
}

func (*ShaderBase) Activate

func (s *ShaderBase) Activate()

func (*ShaderBase) GetAttribLocation

func (s *ShaderBase) GetAttribLocation(name string) int32

func (*ShaderBase) GetUniformBlockIndex

func (s *ShaderBase) GetUniformBlockIndex(name string) uint32

func (*ShaderBase) GetUniformLocation

func (s *ShaderBase) GetUniformLocation(name string) int32

func (*ShaderBase) GlName

func (s *ShaderBase) GlName() uint32

type ShaderBinder

type ShaderBinder struct {
	ObjectBase
	// contains filtered or unexported fields
}

func NewShaderBinder

func NewShaderBinder(shaders map[uint32]Shader, boundStruct any, getBindingPointFunc func() uint32) *ShaderBinder

func (*ShaderBinder) Close

func (b *ShaderBinder) Close()

func (*ShaderBinder) Init

func (b *ShaderBinder) Init() (ok bool)

func (*ShaderBinder) Update

func (b *ShaderBinder) Update(deltaTime int64) (ok bool)

type ShaderBinding

type ShaderBinding struct {
	ObjectBase
	// contains filtered or unexported fields
}

func NewShaderBinding

func NewShaderBinding(shader Shader, boundStruct any, getBindingPointFunc func() uint32) *ShaderBinding

func (*ShaderBinding) Close

func (b *ShaderBinding) Close()

func (*ShaderBinding) Init

func (b *ShaderBinding) Init() (ok bool)

func (*ShaderBinding) UboNames

func (b *ShaderBinding) UboNames() []uint32

func (*ShaderBinding) Update

func (b *ShaderBinding) Update(_ int64) (ok bool)

type ShaderSource

type ShaderSource interface {
	[]byte | string
}

type ShaderTransform

type ShaderTransform struct {
	Origin   mgl32.Vec4
	Position mgl32.Vec4
	Rotation mgl32.Vec4
	Scale    mgl32.Vec4
}

type Shape2D

type Shape2D struct {
	WindowObjectBase
	// contains filtered or unexported fields
}

func NewCircle

func NewCircle(thickness float32) *Shape2D

func NewDot

func NewDot() *Shape2D

func NewQuad

func NewQuad() *Shape2D

func NewShape2D

func NewShape2D() *Shape2D

func NewSquare

func NewSquare(thickness float32) *Shape2D

func NewTriangle

func NewTriangle(thickness float32) *Shape2D

func (*Shape2D) Close

func (s *Shape2D) Close()

func (*Shape2D) Draw

func (s *Shape2D) Draw(deltaTime int64) (ok bool)

func (*Shape2D) FlipUV

func (s *Shape2D) FlipUV(flipped bool) *Shape2D

func (*Shape2D) Init

func (s *Shape2D) Init() (ok bool)

func (*Shape2D) Length

func (s *Shape2D) Length() float32

func (*Shape2D) Resize

func (s *Shape2D) Resize(newWidth, newHeight int)

func (*Shape2D) SetLength

func (s *Shape2D) SetLength(length float32) *Shape2D

func (*Shape2D) SetSides

func (s *Shape2D) SetSides(sides uint) *Shape2D

func (*Shape2D) SetTexture

func (s *Shape2D) SetTexture(texture Texture) *Shape2D

func (*Shape2D) SetThickness

func (s *Shape2D) SetThickness(thickness float32) *Shape2D

func (*Shape2D) SetViewport

func (s *Shape2D) SetViewport(viewport *Viewport) *Shape2D

func (*Shape2D) Sides

func (s *Shape2D) Sides() uint

func (*Shape2D) Texture

func (s *Shape2D) Texture() (texture Texture)

func (*Shape2D) Thickness

func (s *Shape2D) Thickness() float32

func (*Shape2D) Update

func (s *Shape2D) Update(deltaTime int64) (ok bool)

func (*Shape2D) Viewport

func (s *Shape2D) Viewport() *Viewport

type Shape3D

type Shape3D struct {
	WindowObjectBase
	// contains filtered or unexported fields
}

func NewShape3D

func NewShape3D() *Shape3D

func (*Shape3D) Camera

func (s *Shape3D) Camera() Camera

func (*Shape3D) Close

func (s *Shape3D) Close()

func (*Shape3D) Draw

func (s *Shape3D) Draw(deltaTime int64) (ok bool)

func (*Shape3D) Init

func (s *Shape3D) Init() (ok bool)

func (*Shape3D) Lighting

func (s *Shape3D) Lighting() any

func (*Shape3D) Meshes

func (s *Shape3D) Meshes() []*meshInstance

func (*Shape3D) Resize

func (s *Shape3D) Resize(newWidth, newHeight int)

func (*Shape3D) SetCamera

func (s *Shape3D) SetCamera(camera Camera) *Shape3D

func (*Shape3D) SetLighting

func (s *Shape3D) SetLighting(lighting any) *Shape3D

func (*Shape3D) SetModel

func (s *Shape3D) SetModel(model Model) *Shape3D

func (*Shape3D) SetViewport

func (s *Shape3D) SetViewport(viewport *Viewport) *Shape3D

func (*Shape3D) Viewport

func (s *Shape3D) Viewport() *Viewport

type Signal

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

func NewSignal

func NewSignal(label string, bufferSize int) *Signal

func (*Signal) AddFilter

func (s *Signal) AddFilter(filter Filter)

func (*Signal) AddSamples

func (s *Signal) AddSamples(data []float64)

func (*Signal) AddTransformer

func (s *Signal) AddTransformer(transformer Transformer)

func (*Signal) Average

func (s *Signal) Average() float64

func (*Signal) BufferSize

func (s *Signal) BufferSize() int

func (*Signal) Data

func (s *Signal) Data() []float64

func (*Signal) DeltaAverage

func (s *Signal) DeltaAverage() float64

func (*Signal) DeltaStdDev

func (s *Signal) DeltaStdDev(calculateDeltas bool) float64

func (*Signal) DisableFFT

func (s *Signal) DisableFFT()

func (*Signal) EnableFFT

func (s *Signal) EnableFFT(sampleRate float64)

func (*Signal) FFTEnabled

func (s *Signal) FFTEnabled() bool

func (*Signal) FilteredData

func (s *Signal) FilteredData() []float64

func (*Signal) GetFilter

func (s *Signal) GetFilter(name string) Filter

func (*Signal) GetTransformer

func (s *Signal) GetTransformer(name string) Transformer

func (*Signal) Label

func (s *Signal) Label() string

func (*Signal) Lock

func (s *Signal) Lock()

func (*Signal) MaxValue

func (s *Signal) MaxValue() float64

func (*Signal) MinValue

func (s *Signal) MinValue() float64

func (*Signal) SetFFTSampleRate

func (s *Signal) SetFFTSampleRate(rate float64)

func (*Signal) StdDev

func (s *Signal) StdDev() float64

func (*Signal) TransformedData

func (s *Signal) TransformedData() []float64

func (*Signal) TransformedDataLabels

func (s *Signal) TransformedDataLabels() []float64

func (*Signal) Unlock

func (s *Signal) Unlock()

type SignalControl

type SignalControl interface {
	*SignalLine | *SignalGroup
}

type SignalGroup

type SignalGroup struct {
	View
	// contains filtered or unexported fields
}

func NewSignalGroup

func NewSignalGroup(defaultSampleCount int, defaultLineThickness int, colors ...color.RGBA) *SignalGroup

func (*SignalGroup) Add

func (g *SignalGroup) Add(signal *SignalLine) *SignalLine

func (*SignalGroup) Close

func (g *SignalGroup) Close()

func (*SignalGroup) Draw

func (g *SignalGroup) Draw(deltaTime int64) (ok bool)

func (*SignalGroup) EnableDataExportKey

func (g *SignalGroup) EnableDataExportKey(key glfw.Key) *SignalGroup

func (*SignalGroup) EnableInspector

func (g *SignalGroup) EnableInspector(inspectKey ...glfw.Key)

func (*SignalGroup) Init

func (g *SignalGroup) Init() (ok bool)

func (*SignalGroup) InspectorPanel

func (g *SignalGroup) InspectorPanel() *View

func (*SignalGroup) New

func (g *SignalGroup) New(label string) *SignalLine

func (*SignalGroup) Remove

func (g *SignalGroup) Remove(signal *SignalLine) *SignalLine

func (*SignalGroup) RemoveAt

func (g *SignalGroup) RemoveAt(index int)

func (*SignalGroup) Resize

func (g *SignalGroup) Resize(newWidth, newHeight int)

func (*SignalGroup) SetEnabled

func (g *SignalGroup) SetEnabled(enabled bool) Object

func (*SignalGroup) SetInspectorAnchor

func (g *SignalGroup) SetInspectorAnchor(anchor Anchor)

func (*SignalGroup) SetInspectorFontSize

func (g *SignalGroup) SetInspectorFontSize(size float32) *SignalGroup

func (*SignalGroup) SetInspectorMargin

func (g *SignalGroup) SetInspectorMargin(margin Margin) *SignalGroup

func (*SignalGroup) SetInspectorPanelSize

func (g *SignalGroup) SetInspectorPanelSize(size float32) *SignalGroup

func (*SignalGroup) SetWindow

func (g *SignalGroup) SetWindow(window *Window) WindowObject

func (*SignalGroup) Signals

func (g *SignalGroup) Signals() []*SignalLine

func (*SignalGroup) Update

func (g *SignalGroup) Update(deltaTime int64) (ok bool)

type SignalInspector

type SignalInspector struct {
	WindowObjectBase
	// contains filtered or unexported fields
}

func NewSignalInspector

func NewSignalInspector[T SignalControl](parent T) *SignalInspector

func (*SignalInspector) Close

func (i *SignalInspector) Close()

func (*SignalInspector) Draw

func (i *SignalInspector) Draw(deltaTime int64) (ok bool)

func (*SignalInspector) Init

func (i *SignalInspector) Init() (ok bool)

func (*SignalInspector) Panel

func (i *SignalInspector) Panel() *View

func (*SignalInspector) Resize

func (i *SignalInspector) Resize(newWidth, newHeight int)

func (*SignalInspector) SetFontSize

func (i *SignalInspector) SetFontSize(size float32) *SignalInspector

func (*SignalInspector) SetMaintainAspectRatio

func (i *SignalInspector) SetMaintainAspectRatio(maintainAspectRatio bool) WindowObject

func (*SignalInspector) SetPanelSize

func (i *SignalInspector) SetPanelSize(size float32) *SignalInspector

func (*SignalInspector) SetWindow

func (i *SignalInspector) SetWindow(window *Window) WindowObject

func (*SignalInspector) Update

func (i *SignalInspector) Update(deltaTime int64) (ok bool)

type SignalLine

type SignalLine struct {
	View
	Signal
	// contains filtered or unexported fields
}

func NewSignalLine

func NewSignalLine(label string, sampleCount int) *SignalLine

func (*SignalLine) AddSamples

func (l *SignalLine) AddSamples(data []float64)

func (*SignalLine) Close

func (l *SignalLine) Close()

func (*SignalLine) Draw

func (l *SignalLine) Draw(deltaTime int64) (ok bool)

func (*SignalLine) EnableDataExportKey

func (l *SignalLine) EnableDataExportKey(key glfw.Key) *SignalLine

func (*SignalLine) EnableInspector

func (l *SignalLine) EnableInspector(inspectKey ...glfw.Key)

func (*SignalLine) Init

func (l *SignalLine) Init() (ok bool)

func (*SignalLine) InspectorPanel

func (l *SignalLine) InspectorPanel() *View

func (*SignalLine) Label

func (l *SignalLine) Label() *Label

func (*SignalLine) Resize

func (l *SignalLine) Resize(newWidth, newHeight int)

func (*SignalLine) SetColor

func (l *SignalLine) SetColor(rgba color.RGBA) WindowObject

func (*SignalLine) SetInspectorAnchor

func (l *SignalLine) SetInspectorAnchor(anchor Anchor)

func (*SignalLine) SetInspectorFontSize

func (l *SignalLine) SetInspectorFontSize(size float32) *SignalLine

func (*SignalLine) SetInspectorMargin

func (l *SignalLine) SetInspectorMargin(margin Margin) *SignalLine

func (*SignalLine) SetInspectorPanelSize

func (l *SignalLine) SetInspectorPanelSize(size float32) *SignalLine

func (*SignalLine) SetThickness

func (l *SignalLine) SetThickness(thickness uint) *SignalLine

func (*SignalLine) SetWindow

func (l *SignalLine) SetWindow(window *Window) WindowObject

func (*SignalLine) Thickness

func (l *SignalLine) Thickness() uint

func (*SignalLine) Update

func (l *SignalLine) Update(deltaTime int64) (ok bool)

type Slider

type Slider struct {
	View
	// contains filtered or unexported fields
}

func NewSlider

func NewSlider(orientation Orientation, isButtonCircular ...bool) *Slider

func (*Slider) Button

func (s *Slider) Button() *Button

func (*Slider) Close

func (s *Slider) Close()

func (*Slider) Draw

func (s *Slider) Draw(deltaTime int64) (ok bool)

func (*Slider) Init

func (s *Slider) Init() (ok bool)

func (*Slider) OnValueChanged

func (s *Slider) OnValueChanged(handler func(sender WindowObject, value float32)) *Slider

func (*Slider) OnValueChanging

func (s *Slider) OnValueChanging(handler func(sender WindowObject, value float32)) *Slider

func (*Slider) Rail

func (s *Slider) Rail() *Shape2D

func (*Slider) Resize

func (s *Slider) Resize(newWidth, newHeight int)

func (*Slider) SetMouseSurface

func (s *Slider) SetMouseSurface(surface MouseSurface)

func (*Slider) SetValue

func (s *Slider) SetValue(value float32)

func (*Slider) SetWindow

func (s *Slider) SetWindow(window *Window) WindowObject

func (*Slider) Update

func (s *Slider) Update(deltaTime int64) (ok bool)

func (*Slider) Value

func (s *Slider) Value() float32

type TabAction

type TabAction int
const (
	HideOnly TabAction = iota
	DisableOnly
	HideAndDisable
)

type TabGroup

type TabGroup struct {
	WindowObjectBase
	// contains filtered or unexported fields
}

func NewTabGroup

func NewTabGroup(objects ...WindowObject) *TabGroup

func (*TabGroup) Activate

func (g *TabGroup) Activate(index int)

func (*TabGroup) ActiveIndex

func (g *TabGroup) ActiveIndex() int

func (*TabGroup) Close

func (g *TabGroup) Close()

func (*TabGroup) Draw

func (g *TabGroup) Draw(deltaTime int64) (ok bool)

func (*TabGroup) IndexOf

func (g *TabGroup) IndexOf(name string) int

func (*TabGroup) Init

func (g *TabGroup) Init() (ok bool)

func (*TabGroup) NavKeys

func (g *TabGroup) NavKeys() NavKeys

func (*TabGroup) Next

func (g *TabGroup) Next()

func (*TabGroup) Previous

func (g *TabGroup) Previous()

func (*TabGroup) RecursiveMode

func (g *TabGroup) RecursiveMode() (recursive bool)

func (*TabGroup) Resize

func (g *TabGroup) Resize(newWidth, newHeight int)

func (*TabGroup) SetNavKeys

func (g *TabGroup) SetNavKeys(keys NavKeys) *TabGroup

func (*TabGroup) SetRecursiveMode

func (g *TabGroup) SetRecursiveMode(recursive bool) *TabGroup

func (*TabGroup) SetTabAction

func (g *TabGroup) SetTabAction(action TabAction) *TabGroup

func (*TabGroup) TabAction

func (g *TabGroup) TabAction() TabAction

func (*TabGroup) Transition

func (g *TabGroup) Transition(index int, speed ...float64)

func (*TabGroup) TransitionNext

func (g *TabGroup) TransitionNext(speed ...float64)

func (*TabGroup) TransitionPrevious

func (g *TabGroup) TransitionPrevious(speed ...float64)

type TextAlignment

type TextAlignment int

TextAlignment specifies how the text within Label objects should be positioned with respect to the "frame" of the Label, which is based on its scale.

const (
	Centered TextAlignment = iota
	Left
	Right
)

type Texture

type Texture interface {
	GlAsset

	// Width shall return the width of the texture, in pixels.
	Width() int

	// Height shall return the height of the texture, in pixels.
	Height() int
}

Texture assets represent texture maps that can be sampled by shaders by binding them to sampler2D variables.

type Texture2D

type Texture2D struct {
	AssetBase
	// contains filtered or unexported fields
}

func NewTexture2D

func NewTexture2D[T TextureSource](name string, source T, config ...*TextureConfig) *Texture2D

func (*Texture2D) Close

func (t *Texture2D) Close()

func (*Texture2D) GlName

func (t *Texture2D) GlName() uint32

func (*Texture2D) Height

func (t *Texture2D) Height() int

func (*Texture2D) Init

func (t *Texture2D) Init() bool

func (*Texture2D) SetSize

func (t *Texture2D) SetSize(width, height int)

func (*Texture2D) Width

func (t *Texture2D) Width() int

type TextureConfig

type TextureConfig struct {
	FilterQuality QualityLevel
	UWrapMode     TextureWrapMode
	VWrapMode     TextureWrapMode
}

func NewTextureConfig

func NewTextureConfig(filterQuality QualityLevel, wrapMode ...TextureWrapMode) *TextureConfig

func (*TextureConfig) GetFilterConfig

func (c *TextureConfig) GetFilterConfig() (useMipMaps bool, minFilterMode, magFilterMode int32)

type TextureSource

type TextureSource interface {
	[]byte | string | color.RGBA | *image.RGBA | *image.NRGBA
}

type TextureWrapMode

type TextureWrapMode int32

type Transform

type Transform interface {
	ParentTransform() Transform
	SetParentTransform(Transform) Transform

	Origin() mgl32.Vec3
	WorldOrigin() mgl32.Vec3
	SetOrigin(mgl32.Vec3) Transform

	Position() mgl32.Vec3
	WorldPosition() mgl32.Vec3
	SetPosition(mgl32.Vec3) Transform
	SetPositionX(float32) Transform
	SetPositionY(float32) Transform
	SetPositionZ(float32) Transform

	Rotation() mgl32.Vec3
	WorldRotation() mgl32.Vec3
	SetRotation(mgl32.Vec3) Transform
	SetRotationX(float32) Transform
	SetRotationY(float32) Transform
	SetRotationZ(float32) Transform

	Scale() mgl32.Vec3
	WorldScale() mgl32.Vec3
	SetScale(mgl32.Vec3) Transform
	SetScaleX(float32) Transform
	SetScaleY(float32) Transform
	SetScaleZ(float32) Transform

	RotationQuat() mgl32.Quat
	SetRotationQuat(mgl32.Quat) Transform
	WorldMatrix() mgl32.Mat4
}

Transform Drawable objects are expected to have a transform that can be used to position the object in world space and within the context of a hierarchical parent/child structure. This type defines that contract.

type Transformer

type Transformer interface {
	// Name shall return the unique name given to the transformer.
	Name() string
	SetName(string)

	// Enabled shall return true if this transformer should actually have an
	// effect on the data being passed through it.
	Enabled() bool
	SetEnabled(bool)

	// Transform shall perform the actual transformations to the data,
	// with the input provided to the src argument and the output in the
	// dst argument, optionally returning additional data as a float array.
	Transform(dst, src []float64) []float64
}

Transformer instances are used to transform the data being added to a signal, such as to translate from the time domain to the frequency domain.

type TransformerBase

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

func NewTransformerBase

func NewTransformerBase(name string) *TransformerBase

func (*TransformerBase) Enabled

func (t *TransformerBase) Enabled() bool

func (*TransformerBase) Name

func (t *TransformerBase) Name() string

func (*TransformerBase) SampleRate

func (t *TransformerBase) SampleRate() float64

func (*TransformerBase) SetEnabled

func (t *TransformerBase) SetEnabled(enabled bool)

func (*TransformerBase) SetName

func (t *TransformerBase) SetName(name string)

func (*TransformerBase) Transform

func (t *TransformerBase) Transform(dst, src []float64) []float64

type TrueTypeFont

type TrueTypeFont struct {
	AssetBase
	// contains filtered or unexported fields
}

func NewFont

func NewFont[T FontSource](name string, source T) *TrueTypeFont

func (*TrueTypeFont) Close

func (f *TrueTypeFont) Close()

func (*TrueTypeFont) Init

func (f *TrueTypeFont) Init() bool

func (*TrueTypeFont) TTF

func (f *TrueTypeFont) TTF() *truetype.Font

type VertexAttributeLayout

type VertexAttributeLayout int
const (
	// PositionOnlyVaoLayout Expected vertex shader attributes: a_Position
	PositionOnlyVaoLayout VertexAttributeLayout = iota

	// PositionColorVaoLayout Expected vertex shader attributes: a_Position, a_Color
	PositionColorVaoLayout

	// PositionUvVaoLayout Expected vertex shader attributes: a_Position, a_UV
	PositionUvVaoLayout

	// PositionNormalUvVaoLayout Expected vertex shader attributes: a_Position, a_Normal, a_UV
	PositionNormalUvVaoLayout

	// PositionNormalUvTangentsVaoLayout Expected vertex shader attributes: a_Position, a_Normal, a_UV, a_Tangent, a_Bitangent
	PositionNormalUvTangentsVaoLayout
)

type View

type View struct {
	WindowObjectBase
	// contains filtered or unexported fields
}

func NewView

func NewView() *View

func (*View) BlurEnabled

func (v *View) BlurEnabled() bool

func (*View) BlurIntensity

func (v *View) BlurIntensity() float32

func (*View) BorderColor

func (v *View) BorderColor() color.RGBA

func (*View) BorderThickness

func (v *View) BorderThickness() float32

func (*View) Close

func (v *View) Close()

func (*View) Draw

func (v *View) Draw(deltaTime int64) (ok bool)

func (*View) FillColor

func (v *View) FillColor() color.RGBA

func (*View) Init

func (v *View) Init() (ok bool)

func (*View) Resize

func (v *View) Resize(newWidth, newHeight int)

func (*View) SetBlurEnabled

func (v *View) SetBlurEnabled(enabled bool) WindowObject

func (*View) SetBlurIntensity

func (v *View) SetBlurIntensity(intensity float32) WindowObject

func (*View) SetBorderColor

func (v *View) SetBorderColor(rgba color.RGBA) *View

func (*View) SetBorderThickness

func (v *View) SetBorderThickness(thickness float32) *View

func (*View) SetColor

func (v *View) SetColor(rgba color.RGBA) WindowObject

func (*View) SetFillColor

func (v *View) SetFillColor(rgba color.RGBA) *View

func (*View) SetMaintainAspectRatio

func (v *View) SetMaintainAspectRatio(maintainAspectRatio bool) WindowObject

func (*View) SetParent

func (v *View) SetParent(parent WindowObject, recursive ...bool) WindowObject

func (*View) SetTexture

func (v *View) SetTexture(texture *Texture2D) *View

func (*View) SetWindow

func (v *View) SetWindow(window *Window) WindowObject

func (*View) Update

func (v *View) Update(deltaTime int64) (ok bool)

type Viewport

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

func NewViewport

func NewViewport(windowWidth, windowHeight int) *Viewport

func (*Viewport) Get

func (v *Viewport) Get() (x, y, width, height int32)

func (*Viewport) Set

func (v *Viewport) Set(x, y, width, height float32) *Viewport

func (*Viewport) SetWindowSize

func (v *Viewport) SetWindowSize(width, height int) *Viewport

type Window

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

func NewWindow

func NewWindow(hints ...*WindowHints) *Window

func (*Window) AddKeyEventHandler

func (w *Window) AddKeyEventHandler(receiver any, key glfw.Key, action glfw.Action,
	callback func(window *Window, key glfw.Key, action glfw.Action)) *KeyEventHandler

func (*Window) AddObject

func (w *Window) AddObject(object any, waitForInit ...bool)

func (*Window) AddObjects

func (w *Window) AddObjects(objects ...any)

func (*Window) AddService

func (w *Window) AddService(service Service)

func (*Window) AspectRatio

func (w *Window) AspectRatio() (ratio float32)

func (*Window) AspectRatio2D

func (w *Window) AspectRatio2D() (ratio2d mgl32.Vec2)

func (*Window) AspectRatio2DInv

func (w *Window) AspectRatio2DInv() (invRatio2d mgl32.Vec2)

func (*Window) AspectRatioInv

func (w *Window) AspectRatioInv() (invRatio float32)

func (*Window) Assets

func (w *Window) Assets() (lib *AssetLibrary)

func (*Window) Borderless

func (w *Window) Borderless() (borderless bool)

func (*Window) ClearColor

func (w *Window) ClearColor() (rgba color.RGBA)

func (*Window) ClearLabelCache

func (w *Window) ClearLabelCache()

func (*Window) Close

func (w *Window) Close()

func (*Window) CloseObject

func (w *Window) CloseObject(object Closer)

func (*Window) CloseObjectAsync

func (w *Window) CloseObjectAsync(object Closer)

func (*Window) DisableOnBlur

func (w *Window) DisableOnBlur(disableOnBlur bool) *Window

func (*Window) DisposeAllObjects

func (w *Window) DisposeAllObjects()

func (*Window) DisposeAllObjectsAsync

func (w *Window) DisposeAllObjectsAsync()

func (*Window) DisposeAllServices

func (w *Window) DisposeAllServices(ignoreProtection bool)

func (*Window) DisposeAllServicesAsync

func (w *Window) DisposeAllServicesAsync(ignoreProtection bool)

func (*Window) DisposeObject

func (w *Window) DisposeObject(name string)

func (*Window) DisposeObjectAsync

func (w *Window) DisposeObjectAsync(name string)

func (*Window) DisposeService

func (w *Window) DisposeService(service Service)

func (*Window) DisposeServiceAsync

func (w *Window) DisposeServiceAsync(service Service)

func (*Window) EnableFullscreenKey

func (w *Window) EnableFullscreenKey() *Window

func (*Window) EnableMouseTracking

func (w *Window) EnableMouseTracking() *Window

func (*Window) EnableQuitKey

func (w *Window) EnableQuitKey(cancelFuncs ...context.CancelFunc) *Window

func (*Window) GLFW

func (w *Window) GLFW() (glwin *glfw.Window)

func (*Window) GetObject

func (w *Window) GetObject(name string) Object

func (*Window) GetService

func (w *Window) GetService(name string) Service

func (*Window) HasFocus

func (w *Window) HasFocus() (focused bool)

func (*Window) Height

func (w *Window) Height() (height int)

func (*Window) Hide

func (w *Window) Hide()

func (*Window) Init

func (w *Window) Init(glwin *glfw.Window, ctx context.Context)

func (*Window) InitObject

func (w *Window) InitObject(object Initer) (ok bool)

func (*Window) InitObjectAsync

func (w *Window) InitObjectAsync(object Initer)

func (*Window) InitService

func (w *Window) InitService(service Service) (ok bool)

func (*Window) InitServiceAsync

func (w *Window) InitServiceAsync(service Service)

func (*Window) Initialized

func (w *Window) Initialized() bool

func (*Window) IsFullscreen

func (w *Window) IsFullscreen() bool

func (*Window) IsSecondary

func (w *Window) IsSecondary() (secondary bool)

func (*Window) Maximize

func (w *Window) Maximize()

func (*Window) Minimize

func (w *Window) Minimize()

func (*Window) Mouse

func (w *Window) Mouse() *MouseState

func (*Window) MultiSamplingEnabled

func (w *Window) MultiSamplingEnabled() (enabled bool)

func (*Window) Opacity

func (w *Window) Opacity() (alpha uint8)

func (*Window) OverrideMouseState

func (w *Window) OverrideMouseState(state *MouseState)

func (*Window) Position

func (w *Window) Position() (x, y int)

func (*Window) ReadyChan

func (w *Window) ReadyChan() <-chan bool

func (*Window) RemoveAllObjects

func (w *Window) RemoveAllObjects()

func (*Window) RemoveKeyEventHandlers

func (w *Window) RemoveKeyEventHandlers(receiver any)

func (*Window) RemoveObject

func (w *Window) RemoveObject(name string)

func (*Window) RemoveService

func (w *Window) RemoveService(service Service)

func (*Window) Resizable

func (w *Window) Resizable() (resizable bool)

func (*Window) ScaleX

func (w *Window) ScaleX(x float32) (scaledX float32)

func (*Window) ScaleY

func (w *Window) ScaleY(y float32) (scaledY float32)

func (*Window) SetClearColor

func (w *Window) SetClearColor(rgba color.RGBA) *Window

func (*Window) SetFullscreenEnabled

func (w *Window) SetFullscreenEnabled(enabled bool) *Window

func (*Window) SetHeight

func (w *Window) SetHeight(height int) *Window

func (*Window) SetOpacity

func (w *Window) SetOpacity(alpha uint8) *Window

func (*Window) SetPosition

func (w *Window) SetPosition(x, y int) *Window

func (*Window) SetSecondary

func (w *Window) SetSecondary(secondary bool) *Window

func (*Window) SetSize

func (w *Window) SetSize(width, height int) *Window

func (*Window) SetTitle

func (w *Window) SetTitle(title string) *Window

func (*Window) SetWidth

func (w *Window) SetWidth(width int) *Window

func (*Window) Show

func (w *Window) Show()

func (*Window) Size

func (w *Window) Size() (width, height int)

func (*Window) SwapMouseButtons

func (w *Window) SwapMouseButtons(swapped bool) *Window

func (*Window) Title

func (w *Window) Title() (title string)

func (*Window) ToPNG

func (w *Window) ToPNG() []byte

func (*Window) Update

func (w *Window) Update(deltaTime int64)

func (*Window) Width

func (w *Window) Width() (width int)

type WindowHints

type WindowHints struct {
	Borderless    bool
	Resizable     bool
	MultiSampling bool
}

func NewWindowHints

func NewWindowHints(borderless, resizable, multisampling bool) *WindowHints

type WindowObject

type WindowObject interface {
	DrawableObject
	Transform
	Resizer

	Window() *Window
	SetWindow(*Window) WindowObject

	Color() color.RGBA
	SetColor(color.RGBA) WindowObject

	Opacity() uint8
	SetOpacity(uint8) WindowObject

	BlurIntensity() float32
	SetBlurIntensity(float32) WindowObject
	BlurEnabled() bool
	SetBlurEnabled(bool) WindowObject

	Width() float32
	Height() float32
	HalfWidth() float32
	HalfHeight() float32

	MaintainAspectRatio() bool
	SetMaintainAspectRatio(bool) WindowObject

	Anchor() Anchor
	SetAnchor(Anchor) WindowObject

	Margin() *Margin
	SetMargin(Margin) WindowObject
	SetMarginTop(float32) WindowObject
	SetMarginRight(float32) WindowObject
	SetMarginBottom(float32) WindowObject
	SetMarginLeft(float32) WindowObject

	Bounds() *Bounds

	OnResize(func(int, int))
	RefreshLayout()

	Parent() WindowObject
	SetParent(WindowObject, ...bool) WindowObject
	AddChild(WindowObject) WindowObject
	AddChildren(...WindowObject) WindowObject
	RemoveChild(WindowObject)
	RemoveChildren()
	Child(string) WindowObject
	Children() []WindowObject
}

WindowObject objects are drawable objects that are "window-aware," contain additional rendering and positioning properties, and those that allow them to form a hierarchical structure of parent/child objects.

type WindowObjectBase

type WindowObjectBase struct {
	DrawableObjectBase
	ObjectTransform
	// contains filtered or unexported fields
}

func NewWindowObject

func NewWindowObject() *WindowObjectBase

func (*WindowObjectBase) AddChild

func (o *WindowObjectBase) AddChild(child WindowObject) WindowObject

func (*WindowObjectBase) AddChildren

func (o *WindowObjectBase) AddChildren(children ...WindowObject) WindowObject

func (*WindowObjectBase) Anchor

func (o *WindowObjectBase) Anchor() Anchor

func (*WindowObjectBase) BlurEnabled

func (o *WindowObjectBase) BlurEnabled() bool

func (*WindowObjectBase) BlurIntensity

func (o *WindowObjectBase) BlurIntensity() float32

func (*WindowObjectBase) Bounds

func (o *WindowObjectBase) Bounds() *Bounds

func (*WindowObjectBase) Child

func (o *WindowObjectBase) Child(name string) WindowObject

func (*WindowObjectBase) Children

func (o *WindowObjectBase) Children() []WindowObject

func (*WindowObjectBase) Close

func (o *WindowObjectBase) Close()

func (*WindowObjectBase) Color

func (o *WindowObjectBase) Color() color.RGBA

func (*WindowObjectBase) Draw

func (o *WindowObjectBase) Draw(deltaTime int64) (ok bool)

func (*WindowObjectBase) HalfHeight

func (o *WindowObjectBase) HalfHeight() float32

func (*WindowObjectBase) HalfWidth

func (o *WindowObjectBase) HalfWidth() float32

func (*WindowObjectBase) Height

func (o *WindowObjectBase) Height() float32

func (*WindowObjectBase) Init

func (o *WindowObjectBase) Init() (ok bool)

func (*WindowObjectBase) MaintainAspectRatio

func (o *WindowObjectBase) MaintainAspectRatio() bool

func (*WindowObjectBase) Margin

func (o *WindowObjectBase) Margin() *Margin

func (*WindowObjectBase) OnResize

func (o *WindowObjectBase) OnResize(handler func(newWidth, newHeight int))

func (*WindowObjectBase) Opacity

func (o *WindowObjectBase) Opacity() uint8

func (*WindowObjectBase) Parent

func (o *WindowObjectBase) Parent() WindowObject

func (*WindowObjectBase) RefreshLayout

func (o *WindowObjectBase) RefreshLayout()

func (*WindowObjectBase) RemoveChild

func (o *WindowObjectBase) RemoveChild(child WindowObject)

func (*WindowObjectBase) RemoveChildren

func (o *WindowObjectBase) RemoveChildren()

func (*WindowObjectBase) Resize

func (o *WindowObjectBase) Resize(newWidth, newHeight int)

func (*WindowObjectBase) SetAnchor

func (o *WindowObjectBase) SetAnchor(anchor Anchor) WindowObject

func (*WindowObjectBase) SetBlurEnabled

func (o *WindowObjectBase) SetBlurEnabled(enabled bool) WindowObject

func (*WindowObjectBase) SetBlurIntensity

func (o *WindowObjectBase) SetBlurIntensity(intensity float32) WindowObject

func (*WindowObjectBase) SetColor

func (o *WindowObjectBase) SetColor(rgba color.RGBA) WindowObject

func (*WindowObjectBase) SetMaintainAspectRatio

func (o *WindowObjectBase) SetMaintainAspectRatio(maintainAspectRatio bool) WindowObject

func (*WindowObjectBase) SetMargin

func (o *WindowObjectBase) SetMargin(margin Margin) WindowObject

func (*WindowObjectBase) SetMarginBottom

func (o *WindowObjectBase) SetMarginBottom(margin float32) WindowObject

func (*WindowObjectBase) SetMarginLeft

func (o *WindowObjectBase) SetMarginLeft(margin float32) WindowObject

func (*WindowObjectBase) SetMarginRight

func (o *WindowObjectBase) SetMarginRight(margin float32) WindowObject

func (*WindowObjectBase) SetMarginTop

func (o *WindowObjectBase) SetMarginTop(margin float32) WindowObject

func (*WindowObjectBase) SetOpacity

func (o *WindowObjectBase) SetOpacity(alpha uint8) WindowObject

func (*WindowObjectBase) SetParent

func (o *WindowObjectBase) SetParent(parent WindowObject, recursive ...bool) WindowObject

func (*WindowObjectBase) SetWindow

func (o *WindowObjectBase) SetWindow(window *Window) WindowObject

func (*WindowObjectBase) Update

func (o *WindowObjectBase) Update(deltaTime int64) (ok bool)

func (*WindowObjectBase) Width

func (o *WindowObjectBase) Width() float32

func (*WindowObjectBase) Window

func (o *WindowObjectBase) Window() *Window

Jump to

Keyboard shortcuts

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