tetra3d

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2024 License: MIT Imports: 29 Imported by: 7

README

Tetra3D

Ebitengine Discord

SolarLune's Discord

TetraTerm, an easy-to-use tool to visualize your game scene

Tetra3D Logo

It Breeds Fear - Construction Worker

Dark exploration

Tetra3D Docs / Tetra3D Wiki

Quickstart Project Repo

Support

If you want to support development, feel free to check out my itch.io / Steam / Patreon. I also have a Discord server here. Thanks~!

What is Tetra3D?

Tetra3D is a 3D hybrid software / hardware renderer written in Go by means of Ebitengine, primarily for video games. Compared to a professional 3D rendering system like OpenGL or Vulkan, it's slow and buggy, but it's also janky, and I love it for that. Tetra3D is largely implemented in software, but uses the GPU a bit for rendering triangles and for depth testing (by use of shaders to compare and write depth and composite the result onto the finished texture). Depth testing can be turned off for a slight performance increase in exchange for no visual inter-object intersection.

Tetra3D's rendering evokes a similar feeling to primitive 3D game consoles like the PS1, N64, or DS. Being that a largely-software renderer is not nearly fast enough for big, modern 3D titles, the best you're going to get out of Tetra is drawing some 3D elements for your primarily 2D Ebitengine game, or a relatively simple fully 3D game (i.e. something on the level of a PS1, or N64 game). That said, limitation breeds creativity, and I am intrigued at the thought of what people could make with Tetra.

Tetra3D also gives you a Blender add-on to make the Blender > Tetra3D development process flow a bit smoother. See the Releases section for the add-on, and this wiki page for more information.

Why did I make it?

Because there's not really too much of an ability to do 3D for gamedev in Go apart from g3n, go-gl and Raylib-go. I like Go, I like janky 3D, and so, here we are.

It's also interesting to have the ability to spontaneously do things in 3D sometimes. For example, if you were making a 2D game with Ebitengine but wanted to display just a few GUI elements or objects in 3D, Tetra3D should work well for you.

Finally, while this hybrid renderer is not by any means fast, it is relatively simple and easy to use. Any platforms that Ebiten supports should also work for Tetra3D automatically. Basing a 3D framework off of an existing 2D framework also means any improvements or refinements to Ebitengine may be of help to Tetra3D, and it keeps the codebase small and unified between platforms.

Why Tetra3D? Why is it named that?

Because it's like a tetrahedron, a relatively primitive (but visually interesting) 3D shape made of 4 triangles. Otherwise, I had other names, but I didn't really like them very much. "Jank3D" was the second-best one, haha.

How do you get it?

go get github.com/solarlune/tetra3d

Tetra depends on Ebitengine itself for rendering. Tetra3D requires Go v1.16 or above. This minimum required version is somewhat arbitrary, as it could run on an older Go version if a couple of functions (primarily the ones that loads data from a file directly) were changed.

There is an optional Blender add-on as well (tetra3d.py) that can be downloaded from the releases page or from the repo directly (i.e. click on the file and download it). The add-on provides some useful helper functionality that makes using Tetra3D simpler - for more information, check the Wiki.

How do you use it?

Load a scene, render it. A simple 3D framework means a simple 3D API.

Here's an example:


package main

import (
	"errors"
	"fmt"
	"image/color"

	"github.com/solarlune/tetra3d"
	"github.com/hajimehoshi/ebiten/v2"
)

type Game struct {
	GameScene    *tetra3d.Scene
	Camera       *tetra3d.Camera
}

func NewGame() *Game {

	g := &Game{}

	// First, we load a scene from a .gltf or .glb file. LoadGLTFFile takes a filepath and
	// any loading options (nil can be taken as a valid default set of loading options), and 
	// returns a *tetra3d.Library and an error if it was unsuccessful. We can also use 
	// tetra3d.LoadGLTFData() if we don't have access to the host OS's filesystem (if the 
	// assets are embedded, for example).

	library, err := tetra3d.LoadGLTFFile("example.gltf", nil) 

	if err != nil {
		panic(err)
	}

	// A Library is essentially everything that got exported from your 3D modeler - 
	// all of the scenes, meshes, materials, and animations. The ExportedScene of a Library
	// is the scene that was active when the file was exported.

	// We'll clone the ExportedScene so we don't change it irreversibly; making a clone
	// of a Tetra3D resource (Scene, Node, Material, Mesh, Camera, whatever) makes a deep 
	// copy of it.
	g.GameScene = library.ExportedScene.Clone()

	// Tetra3D uses OpenGL's coordinate system (+X = Right, +Y = Up, +Z = Backward [towards the camera]), 
	// in comparison to Blender's coordinate system (+X = Right, +Y = Forward, 
	// +Z = Up). Note that when loading models in via GLTF or DAE, models are
	// converted automatically (so up is +Z in Blender and +Y in Tetra3D automatically).

	// We could create a new Camera as below - we would pass the size of the screen to the 
	// Camera so it can create its own buffer textures (which are *ebiten.Images).

	// g.Camera = tetra3d.NewCamera(ScreenWidth, ScreenHeight)

	// However, we can also just grab an existing camera from the scene if it 
	// were exported from the GLTF file - if exported through Blender's Tetra3D add-on,
	// then the camera size can be easily set from within Blender.

	g.Camera = g.GameScene.Root.Get("Camera").(*tetra3d.Camera)

	// Camera implements the tetra3d.INode interface, which means it can be placed
	// in 3D space and can be parented to another Node somewhere in the scene tree.
	// Models, Lights, and Nodes (which are essentially "empties" one can
	// use for positioning and parenting) can, as well.

	// We can place Models, Cameras, and other Nodes with node.SetWorldPosition() or 
	// node.SetLocalPosition(). There are also variants that take a 3D Vector.

	// The *World variants of positioning functions takes into account absolute space; 
	// the Local variants position Nodes relative to their parents' positioning and 
	// transforms (and is more performant.)
	// You can also move Nodes using Node.Move(x, y, z) / Node.MoveVec(vector).

	// Each Scene has a tree that starts with the Root Node. To add Nodes to the Scene, 
	// parent them to the Scene's base, like so:

	// scene.Root.AddChildren(object)

	// To remove them, you can unparent them from either the parent (Node.RemoveChildren())
	// or the child (Node.Unparent()). When a Node is unparented, it is removed from the scene
	// tree; if you want to destroy the Node, then dropping any references to this Node 
	// at this point would be sufficient.

	// For Cameras, we don't actually need to place them in a scene to view the Scene, since
	// the presence of the Camera in the Scene node tree doesn't impact what it would see.

	// We can see the tree "visually" by printing out the hierarchy:
	fmt.Println(g.GameScene.Root.HierarchyAsString())

	// You can also visualize the scene hierarchy using TetraTerm:
	// https://github.com/SolarLune/tetraterm

	return g
}

func (g *Game) Update() error { return nil }

func (g *Game) Draw(screen *ebiten.Image) {

	// Here, we'll call Camera.Clear() to clear its internal backing texture. This
	// should be called once per frame before drawing your Scene.
	g.Camera.Clear()

	// Now we'll render the Scene from the camera. The Camera's ColorTexture will then 
	// hold the result. 

	// Camera.RenderScene() renders all Nodes in a scene, starting with the 
	// scene's root. You can also use Camera.Render() to simply render a selection of
	// individual Models, or Camera.RenderNodes() to render a subset of a scene tree.
	g.Camera.RenderScene(g.GameScene) 

	// To see the result, we draw the Camera's ColorTexture to the screen. 
	// Before doing so, we'll clear the screen first. In this case, we'll do this 
	// with a color, though we can also go with screen.Clear().
	screen.Fill(color.RGBA{20, 30, 40, 255})

	// Draw the resulting texture to the screen, and you're done! You can 
	// also visualize the depth texture with g.Camera.DepthTexture().
	screen.DrawImage(g.Camera.ColorTexture(), nil) 

	// Note that the resulting texture is indeed just an ordinary *ebiten.Image, so 
	// you can also use this as a texture for a Model's Material, as an example.

}

func (g *Game) Layout(w, h int) (int, int) {
	
	// Here, by simply returning the camera's size, we are essentially
	// scaling the camera's output to the window size and letterboxing as necessary. 

	// If you wanted to extend the camera according to window size, you would 
	// have to resize the camera using the window's new width and height.
	return g.Camera.Size()

}

func main() {

	game := NewGame()

	if err := ebiten.RunGame(game); err != nil {
		panic(err)
	}

}


You can also do collision testing between BoundingObjects, a category of nodes designed for this purpose. As a simplified example:


type Game struct {

	Cube *tetra3d.BoundingAABB
	Capsule *tetra3d.BoundingCapsule

}

func NewGame() *Game {

	g := &Game{}

	// Create a new BoundingCapsule named "player", 1 unit tall with a 
	// 0.25 unit radius for the caps at the ends.
	g.Capsule = tetra3d.NewBoundingCapsule("player", 1, 0.25)

	// Create a new BoundingAABB named "block", of 0.5 width, height, 
	// and depth (in that order).
	g.Cube = tetra3d.NewBoundingAABB("block", 0.5, 0.5, 0.5)

	// Move the cube over on the X axis by 4 units.
	g.Cube.Move(-4, 0, 0)

	return g

}

func (g *Game) Update() {

	// Move the capsule 0.2 units to the right every frame.
	g.Capsule.Move(0.2, 0, 0)

	// Will print the result of the Collision, (or nil), if there was no intersection.
	fmt.Println(g.Capsule.Collision(g.Cube))

}

If you wanted a deeper collision test with multiple objects, you can do so using IBoundingObject.CollisionTest(). Take a look at the Wiki and the bounds example for more info.

That's basically it. Note that Tetra3D is, indeed, a work-in-progress and so will require time to get to a good state. But I feel like it works pretty well as is. Feel free to examine all of the examples in the examples folder. Calling go run . from within their directories will run them - the mouse usually controls the view, and clicking locks and unlocks the view.

There's a quick start project repo available here, as well to help with getting started.

For more information, check out the Wiki for tips and tricks.

What's missing?

The following is a rough to-do list (tasks with checks have been implemented):

  • 3D rendering
  • -- Perspective projection
  • -- Orthographic projection (it's kinda jank, but it works)
  • -- Automatic billboarding
  • -- Sprites (a way to draw 2D images with no perspective changes (if desired), but within 3D space) (not sure?)
  • -- Basic depth sorting (sorting vertices in a model according to distance, sorting models according to distance)
  • -- A depth buffer and depth testing - This is now implemented by means of a depth texture and Kage shader, though the downside is that it requires rendering and compositing the scene into textures twice. Also, it doesn't work on triangles from the same object (as we can't render to the depth texture while reading it for existing depth).
  • -- A more advanced / accurate depth buffer
  • -- Writing depth through some other means than vertex colors for precision This is fine for now, I think.
  • -- Depth testing within the same object - I'm unsure if I will be able to implement this.
  • -- Offscreen Rendering
  • -- Mesh merging - Meshes can be merged together to lessen individual object draw calls.
  • -- Render batching - We can avoid calling Image.DrawTriangles between objects if they share properties (blend mode, material, etc) and it's not too many triangles to push before flushing to the GPU. Perhaps these Materials can have a flag that you can toggle to enable this behavior? (EDIT: This has been partially added by dynamic batching of Models.)
  • -- Texture wrapping (will require rendering with shaders) - This is kind of implemented, but I don't believe it's been implemented for alpha clip materials.
  • -- Draw triangles shapes in 3D space through a function (could be useful for 3D lines, for example)
  • -- 3D Text (2D text, rendered on an appropriately-sized 3D plane)
  • -- -- Typewriter effect
  • -- -- Customizeable cursor
  • -- -- Horizontal alignment
  • -- -- Vertical alignment
  • -- -- Vertical Scrolling
  • -- -- Replace style setting system with dedicated Style object, with a function to flush various style changes to batch and update the Text texture all at once?
  • -- -- Outlines
  • -- -- Shadows
  • -- -- Gradients
  • -- -- -- Other patterns?
  • -- -- Parsing text for per-letter effects (this would probably require rendering the glyphs from a font to individual images to render; could also involve shaders?)
  • -- -- -- Per-letter colors
  • -- -- -- Bold
  • -- -- -- Italics
  • -- -- -- Strikethrough
  • -- -- -- Letters fading in or out, flickering?
  • -- -- -- Letters changing to other glyphs randomly
  • -- -- Additional effects? (Wavy text, shaky text, etc.)
  • -- Multitexturing / Per-triangle Materials
  • -- Perspective-corrected texturing (currently it's affine, see Wikipedia)
  • -- Automatic triangle / mesh subdivision depending on distance
  • -- Automatic level of detail
  • -- Manual level of detail (ability to render a model using various meshes in stages); note that these stages should be accessible at runtime to allow cloning meshes, for example
  • Culling
  • -- Backface culling
  • -- Frustum culling
  • -- Far triangle culling
  • -- Triangle clipping to view (this isn't implemented, but not having it doesn't seem to be too much of a problem for now)
  • -- Sectors - The general idea is that the camera can be set up to only render sectors that it's in / neighboring (up to a customizeable depth)
  • -- -- Some method to have objects appear in multiple Sectors, but not others?
  • -- Occlusion culling - this should be possible using octrees to determine if an object is visible before rendering it; see: https://www.gamedeveloper.com/programming/occlusion-culling-algorithms
  • -- -- Something to reduce overdraw
  • Debug
  • -- Debug text: overall render time, FPS, render call count, vertex count, triangle count, skipped triangle count
  • -- Wireframe debug rendering
  • -- Normal debug rendering
  • Materials
  • -- Basic Texturing
  • -- Ability to use screen coordinates instead of just UV texturing (useful for repeating patterns)
  • -- Replace opaque transparency mode with just automatic transparency mode? I feel like there might be a reason to have opaque separate, but I can't imagine a normal situation where you'd want it when you could just go with auto + setting alpha to 1
  • Animations
  • -- Armature-based animations
  • -- Object transform-based animations
  • -- Blending between animations
  • -- Linear keyframe interpolation
  • -- Constant keyframe interpolation
  • -- Bezier keyframe interpolation
  • -- Morph (mesh-based / shape key) animations (See: https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_017_SimpleMorphTarget.md)
  • -- Mesh swapping during animations, primarily for 2D skeletal animation? (Can be worked around using bones.)
  • Scenes
  • -- Fog
  • -- A node or scenegraph for parenting and simple visibility culling
  • -- Ambient vertex coloring
  • GLTF / GLB model loading
  • -- Vertex colors loading
  • -- Multiple vertex color channels
  • -- UV map loading
  • -- Normal loading
  • -- Transform / full scene loading
  • -- Animation loading
  • -- Camera loading
  • -- Loading world color in as ambient lighting
  • -- Separate .bin loading
  • -- Support for multiple scenes in a single Blend file (was broken due to GLTF exporter changes; working again in Blender 3.3)
  • Blender Add-on
  • -- Export 3D view camera to Scenes for quick iteration
  • -- Object-level color checkbox
  • -- Object-level shadeless checkbox?
  • -- Custom mesh attribute to assign values to vertices, allowing you to, say, "mark" vertices
  • -- Export GLTF on save / on command via button
  • -- Bounds node creation
  • -- Game property export (less clunky version of Blender's vanilla custom properties)
  • -- Collection / group substitution
  • -- -- Overwriting properties through collection instance objects (it would be nice to do this cleanly with a nice UI, but just hamfisting it is fine for now)
  • -- -- Collection instances instantiate their objects in the same location in the tree
  • -- Optional camera size export
  • -- Linking collections from external files
  • -- Material data export
  • -- Option to pack textures or leave them as a path
  • -- Path / 3D Curve support
  • -- Grid support (for pathfinding / linking 3D points together)
  • -- -- Adding costs to pathfinding (should be as simple as adding a cost and currentcost to each GridPoint, then sorting the points to check by cost when pathfinding, then reduce all costs greater than 1 by 1 ) (7/5/23, SolarLune: This works currently, but the pathfinding is still a bit wonky, so it should be looked at again)
  • -- Toggleable option for drawing game property status to screen for each object using the gpu and blf modules
  • -- Game properties should be an ordered slice, rather than a map of property name to property values. (5/22/23, SolarLune: should it be?)
  • -- Consistency between Tetra3D material settings and Blender viewport (so modifying the options in the Tetra3D material panel alters the relevant options in a default material to not mess with it; maybe the material settings should even be wholly disabled for this purpose? It would be great if the models looked the way you'd expect)
  • -- Components (This would also require meta-programming; it'd be nice if components could have elements that were adjustable in Blender. Maybe a "game object" can have a dynamically-written "Components" struct, with space for one of each kind of component, for simplicity (i.e. one physics controller, one gameplay controller, one animation component, etc). There doesn't need to be ways to add or remove components from an object, and components can have any of OnInit, OnAdd, OnRemove, or Update functions to be considered components).
  • DAE model loading
  • -- Vertex colors loading
  • -- UV map loading
  • -- Normal loading
  • -- Transform / full scene loading
  • Lighting
  • -- Smooth shading
  • -- Ambient lights
  • -- Point lights
  • -- Directional lights
  • -- Cube (AABB volume) lights
  • -- Lighting Groups
  • -- Ability to bake lighting to vertex colors
  • -- Ability to bake ambient occlusion to vertex colors
  • -- Specular lighting (shininess)
  • -- Lighting Probes - general idea is to be able to specify a space that has basic (optionally continuously updated) AO and lighting information, so standing a character in this spot makes him greener, that spot redder, that spot darker because he's in the shadows, etc.
  • -- Lightmaps - might be possible with being able to use multiple textures at the same time now?
  • -- Baking AO and lighting into vertex colors? from Blender? It's possible to do already using Cycles, but not very easy or simple.
  • -- Take into account view normal (seems most useful for seeing a dark side if looking at a non-backface-culled triangle that is lit) - This is now done for point lights, but not sun lights
  • -- Per-fragment lighting (by pushing it to the GPU, it would be more efficient and look better, of course)
  • Particles
  • -- Basic particle system support
  • -- Fix layering issue when rendering a particle system underneath another one (visible in the Particles example)
  • Shaders
  • -- Custom fragment shaders
  • -- Normal rendering (useful for, say, screen-space shaders)
  • Collision Testing
  • -- Normal reporting
  • -- Slope reporting
  • -- Contact point reporting
  • -- Varying collision shapes
  • -- Checking multiple collisions at the same time
  • -- Composing collision shapes out of multiple sub-shapes (this can be done by simply creating them, parenting them to some node, and then testing against that node)
  • -- Bounding / Broadphase collision checking
Collision Type Sphere AABB Triangle Capsule
Sphere
AABB ⛔ (buggy)
Triangle ⛔ (buggy) ⛔ (buggy)
Capsule ⛔ (buggy)
Ray
  • -- An actual collision system?

  • 3D Sound (adjusting panning of sound sources based on 3D location?)

  • Optimization

  • -- It might be possible to not have to write depth manually (5/22/23, SolarLune: Not sure what past me meant by this)

  • -- Minimize texture-swapping - should be possible to do now that Kage shaders can handle images of multiple sizes.

  • -- Make NodeFilters work lazily, rather than gathering all nodes in the filter at once

  • -- Reusing vertex indices for adjacent triangles

  • -- Multithreading (particularly for vertex transformations)

  • -- Armature animation improvements?

  • -- Custom Vectors

  • -- -- Vector pools again?

  • -- -- Move over to float32 for mathematics - should be possible with math32 : https://github.com/chewxy/math32

  • -- Matrix pools?

  • -- Raytest optimization

  • -- -- Sphere?

  • -- -- AABB?

  • -- -- Capsule?

  • -- -- Triangles

  • -- -- -- Maybe we can combine contiguous triangles into faces and just check faces?

  • -- -- -- We could use the broadphase system to find triangles that are in the raycast's general area, specifically

  • -- Instead of doing collision testing using triangles directly, we can test against planes / faces if possible to reduce checks?

  • -- Lighting speed improvements

  • -- Resource tracking system to ease cloning elements (i.e. rather than live-cloning Meshes, it would be faster to re-use "dead" Meshes)

  • -- -- Model

  • -- -- Mesh

  • -- Prefer Discrete GPU for computers with both discrete and integrated graphics cards

  • -- Replace *Color with just the plain Color struct (this would be a breaking change)

  • -- Replace color usage with HTML or W3C colors? : https://www.computerhope.com/htmcolor.htm#gray / https://www.computerhope.com/jargon/w/w3c-color-names.htm

  • -- Update to use Generics where possible; we're already on Go 1.18.

  • -- Move utility objects (quaternion, vector, color, text, matrix, treewatcher, etc) to utility package.

  • -- Optimize getting an object by path; maybe this could be done with some kind of string serialization, rather than text parsing?

Again, it's incomplete and jank. However, it's also pretty cool!

Shout-out time~

Huge shout-out to the open-source community:

... For sharing the information and code to make this possible; I would definitely have never been able to create this otherwise.

Documentation

Index

Constants

View Source
const (
	TrackTypePosition = "Pos"
	TrackTypeScale    = "Sca"
	TrackTypeRotation = "Rot"
)
View Source
const (
	InterpolationLinear int = iota
	InterpolationConstant
	InterpolationCubic // Unimplemented
)
View Source
const (
	AccumlateColorModeNone            = iota // No accumulation buffer rendering
	AccumlateColorModeBelow                  // Accumulation buffer is on and applies over time, renders ColorTexture after the accumulation result (which is, then, below)
	AccumlateColorModeAbove                  // Accumulation buffer is on and applies over time, renders ColorTexture before the accumulation result (which is on top)
	AccumlateColorModeSingleLastFrame        // Accumulation buffer is on and renders just the previous frame's ColorTexture result
)
View Source
const (
	TriangleSortModeBackToFront = iota // TriangleSortBackToFront sorts the triangles from back to front (naturally). This is the default.
	TriangleSortModeFrontToBack        // TriangleSortFrontToBack sorts the triangles in reverse order.
	TriangleSortModeNone               // TriangleSortNone doesn't sort the triangles at all; this is the fastest triangle sorting mode, while also being the most graphically inaccurate. Usable if triangles don't visually intersect.
)
View Source
const (
	// TransparencyModeAuto means it will be opaque if the object or material's alpha >= 1, and transparent otherwise.
	TransparencyModeAuto = iota

	// TransparencyModeOpaque means the triangles are rendered to the color and depth buffer as normal.
	TransparencyModeOpaque

	// TransparencyModeAlphaClip means the triangles are rendered to the color and depth buffer, using the alpha of the triangles' texture to "cut out" the triangles.
	TransparencyModeAlphaClip

	// TransparencyModeTransparent means the triangles are not rendered to the depth buffer, but are rendered in a second pass after opaque and alpha-clip triangles. They are automatically sorted from back-to-front.
	TransparencyModeTransparent
)
View Source
const (
	BillboardModeNone          = iota // No billboarding
	BillboardModeFixedVertical        // Billboard to face forward relative to the camera / screen under all circumstances; up is screen up / up relative to the camera, locally (local +Y)
	BillboardModeHorizontal           // Billboard to face towards the camera, but skews as you go above / below the object)
	BillboardModeAll                  // Billboard on all axes
)
View Source
const (
	LightingModeDefault      = iota // Default lighting mode
	LightingModeFixedNormals        // Lighting applies as though faces always point towards light sources; good for 2D sprites
	LightingModeDoubleSided         // Lighting applies for double-sided faces
)
View Source
const (
	AutoBatchNone    = iota // No automatic batching
	AutoBatchDynamic        // Dynamically batch
	AutoBatchStatic         // Statically merge
)
View Source
const (
	ParticleVertexSpawnModeOff        = iota // Particles spawn at the center of the system's root Model.
	ParticleVertexSpawnModeAscending         // Particles spawn at the vertices of the system's root Model. They spawn in ascending order before looping.
	ParticleVertexSpawnModeDescending        // Particles spawn at the vertices of the system's root Model. They spawn in descending order before looping.
	ParticleVertexSpawnModeRandom            // Particles spawn at the vertices of the system's root Model. They spawn in random order.
)
View Source
const (
	SectorDetectionTypeVertices = iota // If sector neighbors are detected by sharing vertex positions
	SectorDetectionTypeAABB            // If sector neighbors are detected by AABB
)
View Source
const (
	FogAdd         = iota // Additive blended fog
	FogSub                // Subtractive blended fog
	FogOverwrite          // Color overwriting fog (mixing base with fog color over depth distance)
	FogTransparent        // Fog influences transparency of the render
)
View Source
const (
	FogCurveLinear = iota
	FogCurveOutCirc
	FogCurveInCirc
)
View Source
const MaxTriangleCount = 21845

Variables

View Source
var ReadableReferences = true

If enabled, Nodes, Materials, and other object types will be represented by their names when printed directly. Otherwise, they will be represented by their pointer locations, like default.

View Source
var WorldBack = NewVector(0, 0, 1)

WorldBack represents a unit vector in the global direction of WorldBack on the right-handed OpenGL / Tetra3D's coordinate system (+Z).

View Source
var WorldDown = WorldUp.Invert()

WorldDown represents a unit vector in the global direction of WorldDown on the right-handed OpenGL / Tetra3D's coordinate system (+Y).

View Source
var WorldForward = WorldBack.Invert()

WorldForward represents a unit vector in the global direction of WorldForward on the right-handed OpenGL / Tetra3D's coordinate system (-Z).

View Source
var WorldLeft = WorldRight.Invert()

WorldLeft represents a unit vector in the global direction of WorldLeft on the right-handed OpenGL / Tetra3D's coordinate system (-X).

View Source
var WorldRight = NewVector(1, 0, 0)

WorldRight represents a unit vector in the global direction of WorldRight on the right-handed OpenGL / Tetra3D's coordinate system (+X).

View Source
var WorldUp = NewVector(0, 1, 0)

WorldUp represents a unit vector in the global direction of WorldUp on the right-handed OpenGL / Tetra3D's coordinate system (+Y).

Functions

func ExtendBase3DShader added in v0.15.0

func ExtendBase3DShader(customFragment string) (*ebiten.Shader, error)

ExtendBase3DShader allows you to make a custom fragment shader that extends the base 3D shader, allowing you to make a shader that has fog and depth testing built-in, as well as access to the combined painted vertex colors and vertex-based lighting. To do this, make a Kage shader, but rename the fragment entry point from "Fragment()" to "CustomFragment()". Otherwise, the arguments are the same - dstPos, srcPos, and color, with color containing both vertex color and lighting data. The return vec4 is also the same - the value that is returned from CustomFragment will be used for fog. To turn off lighting or fog individually, you would simply turn on shadelessness and foglessness in your object's Material (or shadelessness in your Model itself).

func ToDegrees added in v0.9.1

func ToDegrees(radians float64) float64

ToDegrees is a helper function to easily convert radians to degrees for human readability.

func ToRadians added in v0.9.0

func ToRadians(degrees float64) float64

ToRadians is a helper function to easily convert degrees to radians (which is what the rotation-oriented functions in Tetra3D use).

Types

type AOBakeOptions added in v0.10.0

type AOBakeOptions struct {
	TargetChannel  int     // The target vertex color channel to bake the ambient occlusion to.
	OcclusionAngle float64 // How severe the angle must be (in radians) for the occlusion effect to show up.
	Color          Color   // The color for the ambient occlusion.

	// A slice indicating other models that influence AO when baking. If this is empty, the AO will
	// just take effect for triangles within the Model, rather than also taking effect for objects that
	// are too close to the baking Model.
	OtherModels        []*Model
	InterModelDistance float64 // How far the other models in OtherModels must be to influence the baking AO.
}

func NewDefaultAOBakeOptions added in v0.10.0

func NewDefaultAOBakeOptions() *AOBakeOptions

NewDefaultAOBakeOptions creates a new AOBakeOptions struct with default settings.

type AmbientLight added in v0.5.0

type AmbientLight struct {
	*Node
	// contains filtered or unexported fields
}

AmbientLight represents an ambient light that colors the entire Scene.

func NewAmbientLight added in v0.5.0

func NewAmbientLight(name string, r, g, b, energy float32) *AmbientLight

NewAmbientLight returns a new AmbientLight.

func (*AmbientLight) AddChildren added in v0.5.0

func (amb *AmbientLight) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*AmbientLight) Clone added in v0.5.0

func (amb *AmbientLight) Clone() INode

func (*AmbientLight) Color added in v0.5.0

func (amb *AmbientLight) Color() Color

func (*AmbientLight) Energy added in v0.5.0

func (amb *AmbientLight) Energy() float32

func (*AmbientLight) Index added in v0.11.2

func (amb *AmbientLight) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*AmbientLight) IsOn added in v0.10.0

func (amb *AmbientLight) IsOn() bool

func (*AmbientLight) Light added in v0.5.0

func (amb *AmbientLight) Light(meshPart *MeshPart, model *Model, targetColors []Color, onlyVisible bool)

Light returns the light level for the ambient light. It doesn't use the provided Triangle; it takes it as an argument to simply adhere to the Light interface.

func (*AmbientLight) SetColor added in v0.15.0

func (amb *AmbientLight) SetColor(color Color)

func (*AmbientLight) SetEnergy added in v0.15.0

func (amb *AmbientLight) SetEnergy(energy float32)

func (*AmbientLight) SetOn added in v0.10.0

func (amb *AmbientLight) SetOn(on bool)

func (*AmbientLight) Type added in v0.8.1

func (amb *AmbientLight) Type() NodeType

Type returns the NodeType for this object.

func (*AmbientLight) Unparent added in v0.5.0

func (amb *AmbientLight) Unparent()

Unparent unparents the AmbientLight from its parent, removing it from the scenegraph.

type Animation

type Animation struct {
	Name string
	// A Channel represents a set of tracks (one for position, scale, and rotation) for the various nodes contained within the Animation.
	Channels map[string]*AnimationChannel
	Length   float64  // Length of the animation in seconds
	Markers  []Marker // Markers as specified in the Animation from the modeler
	// contains filtered or unexported fields
}

Animation represents an animation of some description; it can have multiple channels, indicating movement, scale, or rotational change of one or more Nodes in the Animation.

func NewAnimation

func NewAnimation(name string) *Animation

NewAnimation creates a new Animation of the name specified.

func (*Animation) AddChannel

func (animation *Animation) AddChannel(name string) *AnimationChannel

func (*Animation) FindMarker added in v0.14.0

func (animation *Animation) FindMarker(markerName string) (Marker, bool)

FindMarker returns a marker, found by name, and a boolean value indicating if a marker by the specified name was found or not.

func (*Animation) Library added in v0.8.1

func (animation *Animation) Library() *Library

Library returns the Library from which this Animation was loaded. If it was created in code, this function would return nil.

func (*Animation) String added in v0.12.0

func (animation *Animation) String() string

type AnimationChannel

type AnimationChannel struct {
	Name   string
	Tracks map[string]*AnimationTrack
	// contains filtered or unexported fields
}

AnimationChannel represents a set of tracks (one for position, scale, and rotation) for the various nodes contained within the Animation.

func NewAnimationChannel

func NewAnimationChannel(name string) *AnimationChannel

func (*AnimationChannel) AddTrack

func (channel *AnimationChannel) AddTrack(trackType string) *AnimationTrack

type AnimationPlayer

type AnimationPlayer struct {
	RootNode        INode
	ChannelsToNodes map[*AnimationChannel]INode
	ChannelsUpdated bool
	Animation       *Animation
	Playhead        float64 // Playhead of the animation. Setting this to 0 restarts the animation.

	PlaySpeed  float64    // Playback speed in percentage - defaults to 1 (100%)
	Playing    bool       // Whether the player is playing back or not.
	FinishMode FinishMode // What to do when the player finishes playback. Defaults to looping.
	OnFinish   func()     // Callback indicating the Animation has completed

	OnMarkerTouch func(marker Marker, animation *Animation) // Callback indicating when the AnimationPlayer has entered a marker

	AnimatedProperties map[INode]AnimationValues // The properties that have been animated

	BlendTime float64 // How much time in seconds to blend between two animations

	// If the AnimationPlayer should play the last frame or not. For example, if you have an animation that starts on frame 1 and goes to frame 10,
	// then if PlayLastFrame is on, it will play all frames, INCLUDING frame 10, and only then repeat (if it's set to repeat).
	// Otherwise, it will only play frames 1 - 9, which can be good if your last frame is a repeat of the first to make a cyclical animation.
	// The default for PlayLastFrame is false.
	PlayLastFrame bool

	// When true, animations will play back relative to the node's transform prior to
	// starting the animation. When false, the animation will play back in absolute space.
	// For example, let's say an animation moved a cube from {0, 1, 2} to {10, 1, 2}.
	// If RelativeMotion is on, then if the cube started at position {3, 3, 3}, it would end up at
	// {13, 4, 5}. If RelativeMotion were off, it would teleport to {0, 1, 2} when the animation started.
	// This has to be set to true or false prior to beginning
	// animation playback to properly take effect.
	RelativeMotion bool
	// contains filtered or unexported fields
}

AnimationPlayer is an object that allows you to play back an animation on a Node.

func NewAnimationPlayer

func NewAnimationPlayer(node INode) *AnimationPlayer

NewAnimationPlayer returns a new AnimationPlayer for the Node.

func (*AnimationPlayer) AfterMarker added in v0.10.0

func (ap *AnimationPlayer) AfterMarker(markerName string) bool

AfterMarker returns if the AnimationPlayer's playhead is after a marker with the specified name.

func (*AnimationPlayer) BeforeMarker added in v0.10.0

func (ap *AnimationPlayer) BeforeMarker(markerName string) bool

BeforeMarker returns if the AnimationPlayer's playhead is before a marker with the specified name.

func (*AnimationPlayer) Clone

func (ap *AnimationPlayer) Clone() *AnimationPlayer

Clone returns a clone of the specified AnimationPlayer.

func (*AnimationPlayer) Finished added in v0.10.0

func (ap *AnimationPlayer) Finished() bool

Finished returns whether the AnimationPlayer is finished playing its current animation.

func (*AnimationPlayer) FinishedPlayingAnimation added in v0.13.0

func (ap *AnimationPlayer) FinishedPlayingAnimation(animName string) bool

FinishedPlayingAnimation returns whether the AnimationPlayer just got finished playing an animation of the specified name.

func (*AnimationPlayer) IsPlaying added in v0.15.0

func (ap *AnimationPlayer) IsPlaying(animName string) bool

IsPlaying returns if the AnimationPlayer is playing an animation of the given name.

func (*AnimationPlayer) Play

func (ap *AnimationPlayer) Play(animationName string) error

Play plays back an animation by name, accessing it through the AnimationPlayer's root node's library. If the animation isn't found, it will return an error.

func (*AnimationPlayer) PlayAnim added in v0.11.1

func (ap *AnimationPlayer) PlayAnim(animation *Animation)

PlayAnim plays the specified animation back, resetting the playhead if the specified animation is not currently playing, or if the animation is paused. If the animation is already playing, Play() does nothing.

func (*AnimationPlayer) SetPlayhead added in v0.13.0

func (ap *AnimationPlayer) SetPlayhead(time float64)

SetPlayhead sets the playhead of the animation player to the specified time in seconds, and also performs an update of the animated nodes.

func (*AnimationPlayer) SetRoot

func (ap *AnimationPlayer) SetRoot(node INode)

SetRoot sets the root node of the animation player to act on. Note that this should be the root node.

func (*AnimationPlayer) Stop added in v0.11.0

func (ap *AnimationPlayer) Stop()

Stop stops the AnimationPlayer's playback. Note that this is fundamentally the same as calling ap.Playing = false (for now).

func (*AnimationPlayer) TouchedMarker added in v0.10.0

func (ap *AnimationPlayer) TouchedMarker(markerName string) bool

TouchedMarker returns if a marker with the specified name was touched this past frame - note that this relies on calling AnimationPlayer.Update().

func (*AnimationPlayer) Update

func (ap *AnimationPlayer) Update(dt float64)

Update updates the animation player by the delta specified in seconds (usually 1/FPS or 1/TARGET FPS), animating the transformation properties of the root node's tree.

type AnimationTrack

type AnimationTrack struct {
	Type          string
	Keyframes     []*Keyframe
	Interpolation int
}

AnimationTrack represents a collection of keyframes that drive an animation type (position, scale or rotation) for a node in an animation.

func (*AnimationTrack) AddKeyframe

func (track *AnimationTrack) AddKeyframe(time float64, data interface{})

AddKeyframe adds a keyframe of the necessary data type to the AnimationTrack.

func (*AnimationTrack) ValueAsQuaternion

func (track *AnimationTrack) ValueAsQuaternion(time float64) (Quaternion, bool)

ValueAsQuaternion returns the Quaternion associated with this AnimationTrack using the given time in seconds, and a boolean indicating if the Quaternion exists (i.e. if this is track has rotation animation data).

func (*AnimationTrack) ValueAsVector

func (track *AnimationTrack) ValueAsVector(time float64) (Vector, bool)

ValueAsVector returns a Vector associated with the current time in seconds, as well as a boolean indicating if the Vector exists (i.e. if the AnimationTrack has location or scale data in the animation). The Vector will be interpolated according to time between keyframes.

type AnimationValues

type AnimationValues struct {
	Position       Vector
	PositionExists bool
	Scale          Vector
	ScaleExists    bool
	Rotation       Quaternion
	RotationExists bool
	// contains filtered or unexported fields
}

AnimationValues indicate the current position, scale, and rotation for a Node.

type BoundingAABB

type BoundingAABB struct {
	*Node

	Dimensions Dimensions // Dimensions represents the size of the AABB after transformation.
	// contains filtered or unexported fields
}

BoundingAABB represents a 3D AABB (Axis-Aligned Bounding Box), a 3D cube of varying width, height, and depth that cannot rotate. The primary purpose of a BoundingAABB is, like the other Bounding* Nodes, to perform intersection testing between itself and other BoundingObject Nodes.

func NewBoundingAABB

func NewBoundingAABB(name string, width, height, depth float64) *BoundingAABB

NewBoundingAABB returns a new BoundingAABB Node.

func (*BoundingAABB) AddChildren added in v0.5.0

func (box *BoundingAABB) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*BoundingAABB) Clone

func (box *BoundingAABB) Clone() INode

Clone returns a new BoundingAABB.

func (*BoundingAABB) ClosestPoint

func (box *BoundingAABB) ClosestPoint(point Vector) Vector

ClosestPoint returns the closest point, to the point given, on the inside or surface of the BoundingAABB in world space.

func (*BoundingAABB) Colliding added in v0.9.1

func (box *BoundingAABB) Colliding(other IBoundingObject) bool

Colliding returns true if the BoundingAABB collides with another IBoundingObject.

func (*BoundingAABB) Collision added in v0.9.1

func (box *BoundingAABB) Collision(other IBoundingObject) *Collision

Collision returns the Collision between the BoundingAABB and the other IBoundingObject. If there is no intersection, the function returns nil. (Note that BoundingAABB > BoundingTriangles collision is buggy at the moment.)

func (*BoundingAABB) CollisionTest added in v0.9.1

func (box *BoundingAABB) CollisionTest(settings CollisionTestSettings) []*Collision

CollisionTest performs a collision test using the provided collision test settings structure. As a nicety, CollisionTest also returns a distance-sorted slice of all of the Collisions (but you should rather handle collisions with intent using the OnCollision function of the CollisionTestSettings struct).

func (*BoundingAABB) ContainsAABB added in v0.15.0

func (box *BoundingAABB) ContainsAABB(other *BoundingAABB) bool

ContainsAABB returns if the calling BoundingAABB contains the provided other BoundingAABB.

func (*BoundingAABB) Index added in v0.11.2

func (box *BoundingAABB) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*BoundingAABB) PointInside added in v0.10.0

func (box *BoundingAABB) PointInside(point Vector) bool

func (*BoundingAABB) SetDimensions

func (box *BoundingAABB) SetDimensions(newWidth, newHeight, newDepth float64)

SetDimensions sets the BoundingAABB's internal dimensions (prior to resizing or rotating the Node).

func (*BoundingAABB) Type added in v0.8.1

func (box *BoundingAABB) Type() NodeType

Type returns the NodeType for this object.

func (*BoundingAABB) Unparent added in v0.11.2

func (box *BoundingAABB) Unparent()

Unparent unparents the Camera from its parent, removing it from the scenegraph.

type BoundingCapsule

type BoundingCapsule struct {
	*Node
	Height float64
	Radius float64
	// contains filtered or unexported fields
}

BoundingCapsule represents a 3D capsule, whose primary purpose is to perform intersection testing between itself and other Bounding Nodes.

func NewBoundingCapsule

func NewBoundingCapsule(name string, height, radius float64) *BoundingCapsule

NewBoundingCapsule returns a new BoundingCapsule instance. Name is the name of the underlying Node for the Capsule, height is the total height of the Capsule, and radius is how big around the capsule is. Height has to be at least radius (otherwise, it would no longer be a capsule).

func (*BoundingCapsule) AddChildren added in v0.5.0

func (capsule *BoundingCapsule) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*BoundingCapsule) Bottom

func (capsule *BoundingCapsule) Bottom() Vector

Bottom returns the world position of the bottom of the BoundingCapsule.

func (*BoundingCapsule) Clone

func (capsule *BoundingCapsule) Clone() INode

Clone returns a new BoundingCapsule.

func (*BoundingCapsule) ClosestPoint

func (capsule *BoundingCapsule) ClosestPoint(point Vector) Vector

ClosestPoint returns the closest point on the capsule's "central line" to the point provided. Essentially, ClosestPoint returns a point along the capsule's line in world coordinates, capped between its bottom and top.

func (*BoundingCapsule) Colliding added in v0.9.1

func (capsule *BoundingCapsule) Colliding(other IBoundingObject) bool

Colliding returns true if the BoundingCapsule is intersecting the other BoundingObject.

func (*BoundingCapsule) Collision added in v0.9.1

func (capsule *BoundingCapsule) Collision(other IBoundingObject) *Collision

Collision returns a Collision struct if the BoundingCapsule is intersecting another BoundingObject. If no intersection is reported, Collision returns nil.

func (*BoundingCapsule) CollisionTest added in v0.9.1

func (capsule *BoundingCapsule) CollisionTest(settings CollisionTestSettings) []*Collision

CollisionTest performs a collision test using the provided collision test settings structure. As a nicety, CollisionTest also returns a distance-sorted slice of all of the Collisions (but you should rather handle collisions with intent using the OnCollision function of the CollisionTestSettings struct).

func (*BoundingCapsule) Index added in v0.11.2

func (capsule *BoundingCapsule) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*BoundingCapsule) PointInside

func (capsule *BoundingCapsule) PointInside(point Vector) bool

PointInside returns true if the point provided is within the capsule.

func (*BoundingCapsule) Top

func (capsule *BoundingCapsule) Top() Vector

Top returns the world position of the top of the BoundingCapsule.

func (*BoundingCapsule) Type added in v0.8.1

func (capsule *BoundingCapsule) Type() NodeType

Type returns the NodeType for this object.

func (*BoundingCapsule) Unparent added in v0.11.2

func (capsule *BoundingCapsule) Unparent()

Unparent unparents the Camera from its parent, removing it from the scenegraph.

func (*BoundingCapsule) WorldRadius

func (capsule *BoundingCapsule) WorldRadius() float64

WorldRadius is the radius of the Capsule in world units, after taking into account its scale.

type BoundingSphere

type BoundingSphere struct {
	*Node
	Radius float64
}

BoundingSphere represents a 3D sphere.

func NewBoundingSphere

func NewBoundingSphere(name string, radius float64) *BoundingSphere

NewBoundingSphere returns a new BoundingSphere instance.

func (*BoundingSphere) AddChildren added in v0.5.0

func (sphere *BoundingSphere) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*BoundingSphere) Clone

func (sphere *BoundingSphere) Clone() INode

Clone returns a new BoundingSphere instance.

func (*BoundingSphere) Colliding added in v0.9.1

func (sphere *BoundingSphere) Colliding(other IBoundingObject) bool

Colliding returns true if the BoundingSphere is intersecting the other BoundingObject.

func (*BoundingSphere) Collision added in v0.9.1

func (sphere *BoundingSphere) Collision(other IBoundingObject) *Collision

Collision returns a Collision if the BoundingSphere is intersecting another BoundingObject. If no intersection is reported, Collision returns nil.

func (*BoundingSphere) CollisionTest added in v0.9.1

func (sphere *BoundingSphere) CollisionTest(settings CollisionTestSettings) []*Collision

CollisionTest performs a collision test using the provided collision test settings structure. As a nicety, CollisionTest also returns a distance-sorted slice of all of the Collisions (but you should rather handle collisions with intent using the OnCollision function of the CollisionTestSettings struct).

func (*BoundingSphere) Index added in v0.11.2

func (sphere *BoundingSphere) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*BoundingSphere) PointInside

func (sphere *BoundingSphere) PointInside(point Vector) bool

PointInside returns whether the given point is inside of the sphere or not.

func (*BoundingSphere) Type added in v0.8.1

func (sphere *BoundingSphere) Type() NodeType

Type returns the NodeType for this object.

func (*BoundingSphere) Unparent added in v0.11.2

func (sphere *BoundingSphere) Unparent()

Unparent unparents the Camera from its parent, removing it from the scenegraph.

func (*BoundingSphere) WorldRadius

func (sphere *BoundingSphere) WorldRadius() float64

WorldRadius returns the radius of the BoundingSphere in world units, after taking into account its scale.

type BoundingTriangles

type BoundingTriangles struct {
	*Node
	BoundingAABB *BoundingAABB
	Broadphase   *Broadphase
	Mesh         *Mesh
}

BoundingTriangles is a Node specifically for detecting a collision between any of the triangles from a mesh instance and another BoundingObject.

func NewBoundingTriangles

func NewBoundingTriangles(name string, mesh *Mesh, broadphaseGridSize float64) *BoundingTriangles

NewBoundingTriangles returns a new BoundingTriangles object. name is the name of the BoundingTriangles node, while mesh is a reference to the Mesh that the BoundingTriangles object should use for collision. broadphaseCellSize is how large the BoundingTriangle's broadphase collision cells should be - larger cells means more triangles are checked at a time when doing collision checks, while larger cells also means fewer broadphase cells need to be checked. Striking a balance is a good idea if you're setting this value by hand (by default, the grid size is the maximum dimension size / 20, rounded up (a grid of at least one cell every 20 Blender Units). A size of 0 disables the usage of the broadphase for collision checks.

func (*BoundingTriangles) AddChildren added in v0.5.0

func (bt *BoundingTriangles) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*BoundingTriangles) Clone added in v0.5.0

func (bt *BoundingTriangles) Clone() INode

Clone returns a new BoundingTriangles Node with the same values set as the original.

func (*BoundingTriangles) Colliding added in v0.9.1

func (bt *BoundingTriangles) Colliding(other IBoundingObject) bool

Colliding returns true if the BoundingTriangles object is intersecting the other specified BoundingObject.

func (*BoundingTriangles) Collision added in v0.9.1

func (bt *BoundingTriangles) Collision(other IBoundingObject) *Collision

Collision returns a Collision if the BoundingTriangles object is intersecting another BoundingObject. If no intersection is reported, Collision returns nil. (Note that BoundingTriangles > AABB collision is buggy at the moment.)

func (*BoundingTriangles) CollisionTest added in v0.9.1

func (bt *BoundingTriangles) CollisionTest(settings CollisionTestSettings) []*Collision

CollisionTest performs a collision test using the provided collision test settings structure. As a nicety, CollisionTest also returns a distance-sorted slice of all of the Collisions (but you should rather handle collisions with intent using the OnCollision function of the CollisionTestSettings struct).

func (*BoundingTriangles) DisableBroadphase added in v0.10.0

func (bt *BoundingTriangles) DisableBroadphase()

DisableBroadphase turns off the broadphase system for collision detection by settings its grid and cell size to 0. To turn broadphase collision back on, simply call Broadphase.Resize(gridSize) with a gridSize value above 0.

func (*BoundingTriangles) Index added in v0.11.2

func (bt *BoundingTriangles) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*BoundingTriangles) Type added in v0.8.1

func (bt *BoundingTriangles) Type() NodeType

Type returns the NodeType for this object.

func (*BoundingTriangles) Unparent added in v0.11.2

func (bt *BoundingTriangles) Unparent()

Unparent unparents the Camera from its parent, removing it from the scenegraph.

func (*BoundingTriangles) UpdateTransform added in v0.10.0

func (bt *BoundingTriangles) UpdateTransform()

Transform returns a Matrix4 indicating the global position, rotation, and scale of the object, transforming it by any parents'. If there's no change between the previous Transform() call and this one, Transform() will return a cached version of the transform for efficiency.

type Broadphase added in v0.10.0

type Broadphase struct {
	GridCellCount int // The number of cells in the broadphase grid

	TriSets [][][][]uint16 // The sets of triangles
	// contains filtered or unexported fields
}

Broadphase is a utility object specifically created to assist with quickly ruling out triangles for collision detection or mesh rendering. This works largely automatically; you should generally not have to tweak this too much. The general idea is that the broadphase is composed of AABBs in a grid layout, completely covering the owning mesh. When you, say, check for a collision against a BoundingTriangles object, it first checks to see if the colliding object is within the BoundingTriangles' overall AABB bounding box. If so, it proceeds to the broadphase check, where it sees which set(s) of triangles the colliding object could be colliding with, and then returns that set for finer examination.

func NewBroadphase added in v0.10.0

func NewBroadphase(gridCellCount int, worldPosition Vector, mesh *Mesh) *Broadphase

NewBroadphase returns a new Broadphase object. gridCellCount is number of cells in the grid. worldPosition is the world position of the broadphase object; this should be a zero vector if it's being used for a mesh, and should be the position of the BoundingTriangles if it's being used for collision testing. mesh is the Mesh to be used for broadphase testing.

func (*Broadphase) Clone added in v0.10.0

func (b *Broadphase) Clone() *Broadphase

Clone clones the Broadphase.

func (*Broadphase) Mesh added in v0.15.0

func (b *Broadphase) Mesh() *Mesh

Mesh returns the mesh that is associated with the Broadphase object.

func (*Broadphase) Resize added in v0.10.0

func (b *Broadphase) Resize(gridSize int)

Resize resizes the Broadphase struct, using the new gridSize for how big in units each cell in the grid should be.

func (*Broadphase) TrianglesFromBoundingObject added in v0.15.0

func (b *Broadphase) TrianglesFromBoundingObject(boundingObject IBoundingObject) Set[uint16]

TrianglesFromBoundingObject returns a set of triangle IDs, based on where the BoundingObject is in relation to the Broadphase owning BoundingTriangles instance. The returned set contains each triangle only once, of course.

type Camera

type Camera struct {
	*Node

	RenderDepth                        bool // If the Camera should attempt to render a depth texture; if this is true, then DepthTexture() will hold the depth texture render results. Defaults to true.
	RenderNormals                      bool // If the Camera should attempt to render a normal texture; if this is true, then NormalTexture() will hold the normal texture render results. Defaults to false.
	SectorRendering                    bool // If the Camera should render using sectors or not; if no sectors are present, then it won't attempt to render with them. Defaults to false.
	SectorRenderDepth                  int  // How far out the Camera renders other sectors. Defaults to 1 (so the current sector and its immediate neighbors).
	PerspectiveCorrectedTextureMapping bool // If the Camera should render textures with perspective corrected texture mapping. Defaults to false.

	// How many lights (sorted by distance) should be used to render each object, maximum. If it's greater than 0,
	// then only that many lights will be considered. If less than or equal to 0 (the default), then all available lights will be used.
	MaxLightCount int

	AccumulateColorMode   int                      // The mode to use when rendering previous frames to the accumulation buffer. Defaults to AccumulateColorModeNone.
	AccumulateDrawOptions *ebiten.DrawImageOptions // Draw image options to use when rendering frames to the accumulation buffer; use this to fade out or color previous frames.

	VertexSnapping float64 // When set to a value > 0, it will snap all rendered models' vertices to a grid of the provided size (so VertexSnapping of 0.1 will snap all rendered positions to 0.1 intervals). Defaults to 0 (off).

	DebugInfo DebugInfo

	// DepthMargin is a margin in percentage on both the near and far plane to leave some
	// distance remaining in the depth buffer for triangle comparison.
	// This ensures that objects that are, for example, close to or far from the camera
	// don't begin Z-fighting unnecessarily. It defaults to 4% (on both ends).
	DepthMargin float64
	// contains filtered or unexported fields
}

Camera represents a camera (where you look from) in Tetra3D.

func NewCamera

func NewCamera(w, h int) *Camera

NewCamera creates a new Camera with the specified width and height.

func (*Camera) AccumulationColorTexture added in v0.8.1

func (camera *Camera) AccumulationColorTexture() *ebiten.Image

AccumulationColorTexture returns the camera's final result accumulation color texture from previous renders. If the Camera's AccumulateColorMode property is set to AccumulateColorModeNone, the function will return nil instead.

func (*Camera) AddChildren

func (camera *Camera) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*Camera) AspectRatio added in v0.8.1

func (camera *Camera) AspectRatio() float64

AspectRatio returns the camera's aspect ratio (width / height).

func (*Camera) Clear

func (camera *Camera) Clear()

Clear should be called at the beginning of a single rendered frame and clears the Camera's backing textures before rendering. It also resets the debug values. This function will use the world's clear color, assuming the Camera is in a Scene that has a World. If the Scene has no World, or the Camera is not in the Scene, then it will clear using transparent black.

func (*Camera) ClearWithColor added in v0.15.0

func (camera *Camera) ClearWithColor(clear Color)

ClearWithColor should be called at the beginning of a single rendered frame and clears the Camera's backing textures to the desired color before rendering. It also resets the debug values.

func (*Camera) ClipToScreen

func (camera *Camera) ClipToScreen(vert Vector) Vector

ClipToScreen projects the pre-transformed vertex in View space and remaps it to screen coordinates.

func (*Camera) Clone

func (camera *Camera) Clone() INode

Clone clones the Camera and returns it.

func (*Camera) ColorTexture

func (camera *Camera) ColorTexture() *ebiten.Image

ColorTexture returns the camera's final result color texture from any previous Render() or RenderNodes() calls.

func (*Camera) CurrentSector added in v0.12.1

func (camera *Camera) CurrentSector() *Sector

CurrentSector returns the current sector the Camera is in, if sector-based rendering is enabled.

func (*Camera) DebugDrawText added in v0.9.1

func (camera *Camera) DebugDrawText(screen *ebiten.Image, txtStr string, posX, posY, textScale float64, color Color)

func (*Camera) DepthTexture

func (camera *Camera) DepthTexture() *ebiten.Image

DepthTexture returns the camera's final result depth texture from any previous Render() or RenderNodes() calls. If Camera.RenderDepth is set to false, the function will return nil instead.

func (*Camera) DrawDebugBoundsColored added in v0.8.1

func (camera *Camera) DrawDebugBoundsColored(screen *ebiten.Image, rootNode INode, options DrawDebugBoundsColoredSettings)

DrawDebugBoundsColored will draw shapes approximating the shapes and positions of BoundingObjects underneath the rootNode. The shapes will be drawn in the color provided for each kind of bounding object to the screen image provided. If the passed color is nil, that kind of shape won't be debug-rendered.

func (*Camera) DrawDebugCenters

func (camera *Camera) DrawDebugCenters(screen *ebiten.Image, rootNode INode, color Color)

DrawDebugCenters draws the center positions of nodes under the rootNode using the color given to the screen image provided.

func (*Camera) DrawDebugDrawCallCount added in v0.8.1

func (camera *Camera) DrawDebugDrawCallCount(screen *ebiten.Image, rootNode INode, textScale float64, color Color)

DrawDebugDrawCallCount draws the draw call count of all visible Models underneath the rootNode in the color provided to the screen image provided.

func (*Camera) DrawDebugDrawOrder added in v0.8.1

func (camera *Camera) DrawDebugDrawOrder(screen *ebiten.Image, rootNode INode, textScale float64, color Color)

DrawDebugDrawOrder draws the drawing order of all triangles of all visible Models underneath the rootNode in the color provided to the screen image provided.

func (*Camera) DrawDebugFrustums added in v0.9.0

func (camera *Camera) DrawDebugFrustums(screen *ebiten.Image, rootNode INode, color Color)

DrawDebugFrustums will draw shapes approximating the frustum spheres for objects underneath the rootNode. The shapes will be drawn in the color provided to the screen image provided.

func (*Camera) DrawDebugNormals

func (camera *Camera) DrawDebugNormals(screen *ebiten.Image, rootNode INode, normalLength float64, color Color)

DrawDebugNormals draws the normals of visible models underneath the rootNode given to the screen. NormalLength is the length of the normal lines in units. Color is the color to draw the normals.

func (*Camera) DrawDebugRenderInfo added in v0.9.1

func (camera *Camera) DrawDebugRenderInfo(screen *ebiten.Image, textScale float64, color Color)

DrawDebugRenderInfo draws render debug information (like number of drawn objects, number of drawn triangles, frame time, etc) at the top-left of the provided screen *ebiten.Image, using the textScale and color provided. Note that the frame-time mentioned here is purely the time that Tetra3D spends sending render commands to the command queue. Any additional time that Ebitengine takes to flush that queue is not included in this average frame-time value, and is not visible outside of debugging and profiling, like with pprof.

func (*Camera) DrawDebugWireframe

func (camera *Camera) DrawDebugWireframe(screen *ebiten.Image, rootNode INode, color Color)

DrawDebugWireframe draws the wireframe triangles of all visible Models underneath the rootNode in the color provided to the screen image provided.

func (*Camera) DynamicRender added in v0.15.0

func (camera *Camera) DynamicRender(settings ...DynamicRenderSettings) error

DynamicRender quickly and easily renders an object with the desired setup. The Camera must be present in a Scene to perform this function.

func (*Camera) Far

func (camera *Camera) Far() float64

Far returns the far plane of a camera.

func (*Camera) FieldOfView

func (camera *Camera) FieldOfView() float64

FieldOfView returns the vertical field of view in degrees.

func (*Camera) Index added in v0.11.2

func (camera *Camera) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*Camera) MouseRayTest added in v0.12.0

func (camera *Camera) MouseRayTest(depth float64, testAgainst ...IBoundingObject) []RayHit

MouseRayTest casts a ray forward from the mouse's position onscreen, testing against the provided IBoundingObjects. depth indicates how far the cast ray should extend forwards in world units. The function returns a slice of RayHit objects indicating objects struck by the ray, sorted from closest to furthest. Note that each object can only be struck once by the raycast, with the exception of BoundingTriangles objects (since a single ray may strike multiple triangles).

func (*Camera) Near

func (camera *Camera) Near() float64

Near returns the near plane of a camera.

func (*Camera) NormalTexture added in v0.12.1

func (camera *Camera) NormalTexture() *ebiten.Image

NormalTexture returns the camera's final result normal texture from any previous Render() or RenderNodes() calls. If Camera.RenderNormals is set to false, the function will return nil instead.

func (*Camera) OrthoScale

func (camera *Camera) OrthoScale() float64

OrthoScale returns the scale of an orthographic camera in world units across (horizontally).

func (*Camera) Perspective

func (camera *Camera) Perspective() bool

Perspective returns whether the Camera is perspective or not (orthographic).

func (*Camera) PointInFrustum added in v0.8.1

func (camera *Camera) PointInFrustum(point Vector) bool

PointInFrustum returns true if the point is visible through the camera frustum.

func (*Camera) Projection

func (camera *Camera) Projection() Matrix4

Projection returns the Camera's projection matrix.

func (*Camera) Render

func (camera *Camera) Render(scene *Scene, lights []ILight, models ...*Model)

Render renders all of the models passed using the provided Scene's properties (fog, for example). Note that if Camera.RenderDepth is false, scenes rendered one after another in multiple Render() calls will be rendered on top of each other in the Camera's texture buffers. Note that each MeshPart of a Model has a maximum renderable triangle count of 21845.

func (*Camera) RenderNodes

func (camera *Camera) RenderNodes(scene *Scene, rootNode INode)

RenderNodes renders all nodes starting with the provided rootNode using the Scene's properties (fog, for example). Note that if Camera.RenderDepth is false, scenes rendered one after another in multiple RenderScene() calls will be rendered on top of each other in the Camera's texture buffers. Note that each MeshPart of a Model has a maximum renderable triangle count of 21845.

func (*Camera) RenderScene added in v0.11.0

func (camera *Camera) RenderScene(scene *Scene)

RenderScene renders the provided Scene. Note that if Camera.RenderDepth is false, scenes rendered one after another in multiple RenderScene() calls will be rendered on top of each other in the Camera's texture buffers. Note that each MeshPart of a Model has a maximum renderable triangle count of 21845.

func (*Camera) RenderSprite3D added in v0.15.0

func (camera *Camera) RenderSprite3D(screen *ebiten.Image, renderSettings ...DrawSprite3dSettings)

RenderSprite3D draws an image on the screen in 2D, but at the screen position of the 3D world position provided, and with depth intersection. This allows you to render 2D elements "at" a 3D position, and can be very useful in situations where you want a sprite to render at 100% size and no perspective or skewing, but still look like it's in the 3D space (like in a game with a fixed camera viewpoint).

func (*Camera) Resize

func (camera *Camera) Resize(w, h int)

Resize resizes the backing texture for the Camera to the specified width and height. If the camera already has a backing texture and the width and height are already set to the specified arguments, then the function does nothing.

func (*Camera) ScreenToWorld added in v0.12.0

func (camera *Camera) ScreenToWorld(x, y, depth float64) Vector

ScreenToWorld converts an x and y position on screen to a 3D point in front of the camera. x and y are values ranging between -0.5 and 0.5 for both the horizontal and vertical axes. The depth argument changes how deep the returned Vector is in 3D world units.

func (*Camera) ScreenToWorldPixels added in v0.15.0

func (camera *Camera) ScreenToWorldPixels(x, y int, depth float64) Vector

ScreenToWorldPixels converts an x and y pixel position on screen to a 3D point in front of the camera. The depth argument changes how deep the returned Vector is in 3D world units.

func (*Camera) SetFar added in v0.12.0

func (camera *Camera) SetFar(far float64)

SetFar sets the far plane of the camera.

func (*Camera) SetFieldOfView added in v0.12.0

func (camera *Camera) SetFieldOfView(fovY float64)

SetFieldOfView sets the vertical field of the view of the camera in degrees.

func (*Camera) SetNear added in v0.12.0

func (camera *Camera) SetNear(near float64)

SetNear sets the near plane of a camera.

func (*Camera) SetOrthoScale added in v0.12.0

func (camera *Camera) SetOrthoScale(scale float64)

SetOrthoScale sets the scale of an orthographic camera in world units across (horizontally).

func (*Camera) SetPerspective

func (camera *Camera) SetPerspective(perspective bool)

SetPerspective sets the Camera's projection to be a perspective (true) or orthographic (false) projection.

func (*Camera) Size added in v0.11.0

func (camera *Camera) Size() (w, h int)

Size returns the width and height of the camera's backing color texture. All of the Camera's textures are the same size, so these same size values can also be used for the depth texture, the accumulation buffer, etc.

func (*Camera) SphereInFrustum added in v0.8.1

func (camera *Camera) SphereInFrustum(sphere *BoundingSphere) bool

SphereInFrustum returns true if the sphere would be visible through the camera frustum.

func (*Camera) Type added in v0.8.1

func (camera *Camera) Type() NodeType

Type returns the NodeType for this object.

func (*Camera) Unparent

func (camera *Camera) Unparent()

Unparent unparents the Camera from its parent, removing it from the scenegraph.

func (*Camera) ViewMatrix

func (camera *Camera) ViewMatrix() Matrix4

ViewMatrix returns the Camera's view matrix.

func (*Camera) WorldToClip

func (camera *Camera) WorldToClip(vert Vector) Vector

WorldToClip transforms a 3D position in the world to clip coordinates (before screen normalization).

func (*Camera) WorldToScreen

func (camera *Camera) WorldToScreen(vert Vector) Vector

WorldToScreen transforms a 3D position in the world to a 2D vector, with X and Y ranging from -1 to 1. The Z coordinate indicates depth away from the camera in 3D world units.

func (*Camera) WorldToScreenPixels added in v0.15.0

func (camera *Camera) WorldToScreenPixels(vert Vector) Vector

WorldToScreenPixels transforms a 3D position in the world to a position onscreen, with X and Y representing the pixels. The Z coordinate indicates depth away from the camera in 3D world units.

func (*Camera) WorldUnitToViewRangePercentage added in v0.14.0

func (camera *Camera) WorldUnitToViewRangePercentage(unit float64) float64

WorldUnitToViewRangePercentage converts a unit of world space into a percentage of the view range. Basically, let's say a camera's far range is 100 and its near range is 0. If you called camera.WorldUnitToViewRangePercentage(50), it would return 0.5. This function is primarily useful for custom depth functions operating on Materials.

type Collision added in v0.9.1

type Collision struct {
	BoundingObject IBoundingObject // The BoundingObject collided with
	Intersections  []*Intersection // The slice of Intersections, one for each object or triangle intersected with, arranged in order of distance (far to close).
}

Collision represents the result of a collision test. A Collision test may result in multiple intersections, and so an Collision holds each of these individual intersections in its Intersections slice. The intersections are sorted in order of distance from the starting point of the intersection (the center of the colliding sphere / aabb, the closest point in the capsule, the center of the closest triangle, etc) to the contact point.

func CollisionTestAABB added in v0.15.0

func CollisionTestAABB(x, y, z, width, height, depth float64, settings CollisionTestSettings) []*Collision

CollisionTestAABB performs a quick bounding AABB check at the specified x, y, and z position using the collision settings provided. The bounding AABB will have the provided width, height, and depth. The function will return a slice of successful Collisions, sorted by distance from closest to furthest. If no collisions were found, the function will return an empty slice. Note that AABB tests with BoundingTriangles are currently buggy.

func CollisionTestAABBVec added in v0.15.0

func CollisionTestAABBVec(position, size Vector, settings CollisionTestSettings) []*Collision

CollisionTestAABBVec places a bounding AABB at the position given with the specified size to perform a collision test. Note that AABB tests with BoundingTriangles are currently buggy. The function will return a slice of successful Collisions, sorted by distance from closest to furthest. If no collisions were found, the function will return an empty slice.

func CollisionTestCapsule added in v0.15.0

func CollisionTestCapsule(x, y, z, radius, height float64, settings CollisionTestSettings) []*Collision

CollisionTestCapsule performs a quick bounding capsule check at the specified x, y, and z position using the collision settings provided. The bounding capsule will have the provided radius and height. The function will return a slice of successful Collisions, sorted by distance from closest to furthest. If no collisions were found, the function will return an empty slice.

func CollisionTestCapsuleVec added in v0.15.0

func CollisionTestCapsuleVec(position Vector, radius, height float64, settings CollisionTestSettings) []*Collision

CollisionTestCapsuleVec places a bounding capsule at the position given with the specified radius and height to perform a collision test The function will return a slice of successful Collisions, sorted by distance from closest to furthest. If no collisions were found, the function will return an empty slice.

func CollisionTestSphere added in v0.15.0

func CollisionTestSphere(x, y, z, radius float64, settings CollisionTestSettings) []*Collision

CollisionTestSphere performs a quick bounding sphere check at the specified X, Y, and Z position with the radius given, against the bounding objects provided in "others". The function will return a slice of successful Collisions, sorted by distance from closest to furthest. If no collisions were found, the function will return an empty slice.

func CollisionTestSphereVec added in v0.15.0

func CollisionTestSphereVec(position Vector, radius float64, settings CollisionTestSettings) []*Collision

CollisionTestSphereVec performs a quick bounding sphere check at the specified position with the radius given, against the bounding objects provided in "others". The function will return a slice of successful Collisions, sorted by distance from closest to furthest. If no collisions were found, the function will return an empty slice.

func CommonCollisionTest added in v0.11.0

func CommonCollisionTest(node INode, settings CollisionTestSettings) []*Collision

func (*Collision) AverageContactPoint added in v0.9.1

func (result *Collision) AverageContactPoint() Vector

AverageContactPoint returns the average world contact point out of the contact points of all Intersections contained within the Collision.

func (*Collision) AverageMTV added in v0.9.1

func (col *Collision) AverageMTV() Vector

AverageMTV returns the average MTV (minimum translation vector) from all Intersections contained within the Collision. To be specific, this isn't actually the pure average, but rather is the result of adding together all MTVs from Intersections in the Collision for the direction, and using the greatest MTV's magnitude for the distance of the returned vector. In other words, AverageMTV returns the MTV to move in that should resolve all intersections from the Collision.

func (*Collision) AverageNormal added in v0.10.0

func (col *Collision) AverageNormal() Vector

AverageNormal returns the average normal vector from all Intersections contained within the Collision.

func (*Collision) AverageSlope added in v0.9.1

func (result *Collision) AverageSlope() float64

AverageSlope returns the average slope of the Collision (ranging from 0, pointing straight up, to pi pointing straight down). This average is spread across all intersections contained within the Collision.

func (*Collision) SlideAgainstAverageNormal added in v0.10.0

func (col *Collision) SlideAgainstAverageNormal(movementVec Vector) Vector

SlideAgainstAverageNormal takes an input movement vector and alters it to slide against the Collision's average normal.

type CollisionTestSettings added in v0.11.0

type CollisionTestSettings struct {
	// HandleCollision is a callback function that is called when a valid collision test happens between the
	// calling object and one of the valid INodes contained within the Others slice. The callback should return a boolean
	// indicating if the test should continue after evaluating this collision (true) or not (false).
	//
	// Because this function is called whenever a Collision is found, anything done in this function will influence
	// following possible Collisions. To illustrate this, let's say that you had object A that is colliding with objects B and C.
	// If the collision with B is detected first, and you move A away so that it is no longer colliding with B or C, then the collision
	// with C would not be detected (and HandleCollision would not be called in this case).
	//
	// This being the case, HandleCollision is not guaranteed to be called in any fixed order (so in the above example,
	// it could detect a collision with B first, OR C first). If you need collisions to be checked in order of distance,
	// step through them manually with the results of CollisionTest(), rather than handling them individually with HandleCollision.
	HandleCollision func(col *Collision) bool

	// Others is a slice of INodes to check for collision against.
	// A Collision test tests against all recursive children of the Others slice, testing against specifically the
	// BoundingObjects in those trees.
	// To exemplify this, if you had a Model that had a BoundingObject child, and then added the Model to the Others slice,
	// the Model's children would be tested for collision (which means the BoundingObject), and the Model would be the
	// collided object. Of course, if you simply tested the BoundingObject directly, then it would return the BoundingObject as the collided
	// object in the Collision object returned.
	Others []IBoundingObject
}

CollisionTestSettings controls how a CollisionTest() call evaluates.

type Color

type Color struct {
	R, G, B, A float32
}

Color represents a color, containing R, G, B, and A components, each expected to range from 0 to 1.

func NewColor

func NewColor(r, g, b, a float32) Color

NewColor returns a new Color, with the provided R, G, B, and A components expected to range from 0 to 1.

func NewColorFromHSV added in v0.8.1

func NewColorFromHSV(h, s, v float64) Color

NewColorFromHSV returns a new color, using hue, saturation, and value numbers, each ranging from 0 to 1. A hue of 0 is red, while 1 is also red, but on the other end of the spectrum. Cribbed from: https://github.com/lucasb-eyer/go-colorful/blob/master/colors.go

func NewColorFromHexString added in v0.10.0

func NewColorFromHexString(hex string) Color

func NewColorRandom added in v0.14.0

func NewColorRandom(min, max float32, grayscale bool) Color

NewColorRandom creates a randomized color, with each component lying between the minimum and maximum values.

func (Color) Add added in v0.8.1

func (color Color) Add(other Color) Color

Add adds the provided Color to the existing Color.

func (Color) AddAlpha added in v0.15.0

func (c Color) AddAlpha(alpha float32) Color

AddAlpha adds the provided alpha amount to the Color

func (Color) AddRGBA added in v0.8.1

func (color Color) AddRGBA(r, g, b, a float32) Color

AddRGBA adds the provided R, G, B, and A values to the color as provided. The components are expected to range from 0 to 1.

func (Color) ConvertTosRGB

func (color Color) ConvertTosRGB() Color

ConvertTosRGB() converts the color's R, G, and B components to the sRGB color space. This is used to convert colors from their values in GLTF to how they should appear on the screen. See: https://en.wikipedia.org/wiki/SRGB

func (Color) Hue added in v0.14.0

func (color Color) Hue() float64

Hue returns the hue of the color as a value ranging from 0 to 1.

func (Color) Lerp added in v0.15.0

func (c Color) Lerp(other Color, percentage float64) Color

Lerp linearly interpolates the color from the starting color to the target by the percentage given.

func (Color) LerpRGBA added in v0.15.0

func (c Color) LerpRGBA(r, g, b, a, percentage float64) Color

Lerp linearly interpolates the color from the starting color to the target by the percentage given.

func (Color) Mix added in v0.10.0

func (color Color) Mix(other Color, percentage float32) Color

Mix mixes the calling Color with the other Color, mixed to the percentage given (ranging from 0 - 1).

func (Color) Multiply added in v0.8.1

func (color Color) Multiply(other Color) Color

Multiply multiplies the existing Color by the provided Color.

func (Color) MultiplyRGBA added in v0.8.1

func (color Color) MultiplyRGBA(scalarR, scalarG, scalarB, scalarA float32) Color

MultiplyRGBA multiplies the color's RGBA channels by the provided R, G, B, and A scalar values.

func (Color) MultiplyScalarRGB added in v0.14.0

func (color Color) MultiplyScalarRGB(scalar float32) Color

func (Color) MultiplyScalarRGBA added in v0.14.0

func (color Color) MultiplyScalarRGBA(scalar float32) Color

func (Color) Saturation added in v0.14.0

func (color Color) Saturation() float64

Saturation returns the saturation of the color as a value ranging from 0 to 1.

func (Color) SetAlpha added in v0.10.0

func (color Color) SetAlpha(alpha float32) Color

SetAlpha returns a copy of the the Color with the alpha set to the provided alpha value.

func (Color) SetHue added in v0.14.0

func (color Color) SetHue(h float64) Color

SetHue returns a copy of the color with the hue set to the specified value. Hue goes through the rainbow, starting with red, and ranges from 0 to 1.

func (Color) SetSaturation added in v0.14.0

func (color Color) SetSaturation(s float64) Color

SetSaturation returns a copy of the color with the saturation of the color set to the specified value. Saturation ranges from 0 to 1.

func (Color) SetValue added in v0.14.0

func (color Color) SetValue(v float64) Color

SetValue returns a copy of the color with the value of the color set to the specified value. Value ranges from 0 to 1.

func (Color) String added in v0.13.0

func (color Color) String() string

func (Color) Sub added in v0.10.0

func (color Color) Sub(other Color) Color

Sub subtracts the other Color from the calling Color instance.

func (Color) SubAlpha added in v0.15.0

func (c Color) SubAlpha(alpha float32) Color

SubAlpha adds the provided alpha amount to the Color

func (Color) SubRGBA added in v0.13.0

func (color Color) SubRGBA(r, g, b, a float32) Color

Sub subtracts the other Color from the calling Color instance.

func (Color) ToFloat32s added in v0.8.1

func (color Color) ToFloat32s() (float32, float32, float32, float32)

ToFloat32s returns the Color as four float32 in the order R, G, B, and A.

func (Color) ToFloat64s added in v0.5.1

func (color Color) ToFloat64s() (float64, float64, float64, float64)

ToFloat64s returns four float64 values for each channel in the Color in the order R, G, B, and A.

func (Color) ToRGBA64 added in v0.5.1

func (c Color) ToRGBA64() color.RGBA64

ToRGBA64 converts a color to a color.RGBA64 instance.

func (Color) Value added in v0.14.0

func (color Color) Value() float64

Value returns the value of the color as a value, ranging from 0 to 1.

type ColorCurve added in v0.10.0

type ColorCurve struct {
	Points []ColorCurvePoint
}

ColorCurve represents a range of colors that a value of 0 to 1 can interpolate between.

func NewColorCurve added in v0.10.0

func NewColorCurve() ColorCurve

NewColorCurve creats a new ColorCurve.

func (*ColorCurve) Add added in v0.10.0

func (cc *ColorCurve) Add(color Color, percentage float64)

Add adds a color point to the ColorCurve with the color and percentage provided (from 0-1).

func (*ColorCurve) AddRGBA added in v0.10.0

func (cc *ColorCurve) AddRGBA(r, g, b, a float32, percentage float64)

AddRGBA adds a point to the ColorCurve, with r, g, b, and a being the color and the percentage being a number between 0 and 1 indicating the .

func (ColorCurve) Clone added in v0.10.0

func (cc ColorCurve) Clone() ColorCurve

Clone creates a duplicate ColorCurve.

func (ColorCurve) Color added in v0.10.0

func (cc ColorCurve) Color(perc float64) Color

Color returns the Color for the given percentage in the color curve. For example, if you have a curve composed of the colors {0, 0, 0, 0} at 0 and {1, 1, 1, 1} at 1, then calling Curve.Color(0.5) would return {0.5, 0.5, 0.5, 0.5}.

type ColorCurvePoint added in v0.10.0

type ColorCurvePoint struct {
	Color      Color
	Percentage float64
}

ColorCurvePoint indicates an individual color point in a color curve.

type CubeLight added in v0.10.0

type CubeLight struct {
	*Node
	Dimensions Dimensions // The overall dimensions of the CubeLight.

	On bool // If the CubeLight is on or not
	// A value between 0 and 1 indicating how much opposite faces are still lit within the volume (i.e. at LightBleed = 0.0,
	// faces away from the light are dark; at 1.0, faces away from the light are fully illuminated)
	Bleed         float64
	LightingAngle Vector // The direction in which light is shining. Defaults to local Y down (0, -1, 0).
	// contains filtered or unexported fields
}

CubeLight represents an AABB volume that lights triangles.

func NewCubeLight added in v0.10.0

func NewCubeLight(name string, dimensions Dimensions) *CubeLight

NewCubeLight creates a new CubeLight with the given dimensions.

func NewCubeLightFromModel added in v0.10.0

func NewCubeLightFromModel(name string, model *Model) *CubeLight

NewCubeLightFromModel creates a new CubeLight from the Model's dimensions and world transform. Note that this does not add it to the Model's hierarchy in any way - the newly created CubeLight is still its own Node.

func (*CubeLight) AddChildren added in v0.10.0

func (cube *CubeLight) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*CubeLight) Clone added in v0.10.0

func (cube *CubeLight) Clone() INode

Clone clones the CubeLight, returning a deep copy.

func (*CubeLight) Color added in v0.10.0

func (cube *CubeLight) Color() Color

func (*CubeLight) Energy added in v0.10.0

func (cube *CubeLight) Energy() float32

func (*CubeLight) Index added in v0.11.2

func (cube *CubeLight) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*CubeLight) IsOn added in v0.10.0

func (cube *CubeLight) IsOn() bool

IsOn returns if the CubeLight is on or not.

func (*CubeLight) Light added in v0.10.0

func (cube *CubeLight) Light(meshPart *MeshPart, model *Model, targetColors []Color, onlyVisible bool)

Light returns the R, G, and B values for the PointLight for all vertices of a given Triangle.

func (*CubeLight) SetColor added in v0.15.0

func (cube *CubeLight) SetColor(color Color)

func (*CubeLight) SetEnergy added in v0.15.0

func (cube *CubeLight) SetEnergy(energy float32)

func (*CubeLight) SetOn added in v0.10.0

func (cube *CubeLight) SetOn(on bool)

SetOn sets the CubeLight to be on or off.

func (*CubeLight) TransformedDimensions added in v0.10.0

func (cube *CubeLight) TransformedDimensions() Dimensions

TransformedDimensions returns the AABB volume dimensions of the CubeLight as they have been scaled, rotated, and positioned to follow the CubeLight's node.

func (*CubeLight) Type added in v0.10.0

func (cube *CubeLight) Type() NodeType

Type returns the type of INode this is (NodeTypeCubeLight).

func (*CubeLight) Unparent added in v0.10.0

func (cube *CubeLight) Unparent()

Unparent unparents the CubeLight from its parent, removing it from the scenegraph.

type DaeLoadOptions

type DaeLoadOptions struct {
	CorrectYUp bool // Whether to correct Z being up for Blender importing.
}

DaeLoadOptions represents options one can use to tweak how .dae files are loaded into Tetra3D.

func DefaultDaeLoadOptions

func DefaultDaeLoadOptions() *DaeLoadOptions

DefaultDaeLoadOptions returns a default instance of DaeLoadOptions.

type Data

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

func (*Data) AsQuaternion

func (data *Data) AsQuaternion() Quaternion

func (*Data) AsVector

func (data *Data) AsVector() Vector

type DebugInfo

type DebugInfo struct {
	FrameTime     time.Duration // Amount of CPU frame time spent transforming vertices and calling Image.DrawTriangles. Doesn't include time ebitengine spends flushing the command queue.
	AnimationTime time.Duration // Amount of CPU frame time spent animating vertices.
	LightTime     time.Duration // Amount of CPU frame time spent lighting vertices.

	DrawnParts       int // Number of draw calls, excluding those invisible or culled based on distance
	TotalParts       int // Total number of draw calls
	BatchedParts     int // Total batched number of draw calls
	DrawnTris        int // Number of drawn triangles, excluding those hidden from backface culling
	TotalTris        int // Total number of triangles
	LightCount       int // Total number of lights
	ActiveLightCount int // Total active number of lights
	// contains filtered or unexported fields
}

DebugInfo is a struct that holds debugging information for a Camera's render pass. These values are reset when Camera.Clear() is called.

type Dimensions

type Dimensions struct {
	Min, Max Vector
}

Dimensions represents the minimum and maximum spatial dimensions of a Mesh arranged in a 2-space Vector slice.

func NewDimensionsFromPoints added in v0.10.0

func NewDimensionsFromPoints(points ...Vector) Dimensions

NewDimensionsFromPoints creates a new Dimensions struct from the given series of positions.

func NewEmptyDimensions added in v0.11.0

func NewEmptyDimensions() Dimensions

func (Dimensions) Center

func (dim Dimensions) Center() Vector

Center returns the center point inbetween the two corners of the dimension set.

func (Dimensions) Clamp added in v0.11.0

func (dim Dimensions) Clamp(position Vector) Vector

Clamp limits the provided position vector to be within the dimensions set.

func (Dimensions) Depth

func (dim Dimensions) Depth() float64

Depth returns the total difference between the minimum and maximum Z values.

func (Dimensions) Height

func (dim Dimensions) Height() float64

Height returns the total difference between the minimum and maximum Y values.

func (Dimensions) Inside added in v0.10.0

func (dim Dimensions) Inside(position Vector) bool

Inside returns if a position is inside a set of dimensions.

func (Dimensions) MaxDimension added in v0.8.1

func (dim Dimensions) MaxDimension() float64

MaxDimension returns the maximum value from all of the axes in the Dimensions. For example, if the Dimensions have a min of [-1, -2, -2], and a max of [6, 1.5, 1], Max() will return 7 for the X axis, as it's the largest distance between all axes.

func (Dimensions) MaxSpan

func (dim Dimensions) MaxSpan() float64

MaxSpan returns the maximum span between the corners of the dimension set.

func (Dimensions) Size added in v0.10.0

func (dim Dimensions) Size() Vector

func (Dimensions) Width

func (dim Dimensions) Width() float64

Width returns the total difference between the minimum and maximum X values.

type DirectionalLight added in v0.5.0

type DirectionalLight struct {
	*Node

	On bool // If the light is on and contributing to the scene.
	// contains filtered or unexported fields
}

DirectionalLight represents a directional light of infinite distance.

func NewDirectionalLight added in v0.5.0

func NewDirectionalLight(name string, r, g, b, energy float32) *DirectionalLight

NewDirectionalLight creates a new Directional Light with the specified RGB color and energy (assuming 1.0 energy is standard / "100%" lighting).

func (*DirectionalLight) AddChildren added in v0.5.0

func (sun *DirectionalLight) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*DirectionalLight) Clone added in v0.5.0

func (sun *DirectionalLight) Clone() INode

Clone returns a new DirectionalLight clone from the given DirectionalLight.

func (*DirectionalLight) Color added in v0.5.0

func (d *DirectionalLight) Color() Color

func (*DirectionalLight) Energy added in v0.5.0

func (d *DirectionalLight) Energy() float32

func (*DirectionalLight) Index added in v0.11.2

func (sun *DirectionalLight) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*DirectionalLight) IsOn added in v0.10.0

func (sun *DirectionalLight) IsOn() bool

func (*DirectionalLight) Light added in v0.5.0

func (sun *DirectionalLight) Light(meshPart *MeshPart, model *Model, targetColors []Color, onlyVisible bool)

Light returns the R, G, and B values for the DirectionalLight for each vertex of the provided Triangle.

func (*DirectionalLight) SetColor added in v0.15.0

func (d *DirectionalLight) SetColor(color Color)

func (*DirectionalLight) SetEnergy added in v0.15.0

func (d *DirectionalLight) SetEnergy(energy float32)

func (*DirectionalLight) SetOn added in v0.10.0

func (sun *DirectionalLight) SetOn(on bool)

func (*DirectionalLight) Type added in v0.8.1

func (sun *DirectionalLight) Type() NodeType

Type returns the NodeType for this object.

func (*DirectionalLight) Unparent added in v0.5.0

func (sun *DirectionalLight) Unparent()

Unparent unparents the DirectionalLight from its parent, removing it from the scenegraph.

type DrawDebugBoundsColoredSettings added in v0.14.0

type DrawDebugBoundsColoredSettings struct {
	RenderAABBs         bool
	AABBColor           Color
	RenderSpheres       bool
	SphereColor         Color
	RenderCapsules      bool
	CapsuleColor        Color
	RenderTriangles     bool
	TrianglesColor      Color
	RenderTrianglesAABB bool
	TrianglesAABBColor  Color
	RenderBroadphase    bool
	BroadphaseColor     Color
}

func DefaultDrawDebugBoundsSettings added in v0.14.0

func DefaultDrawDebugBoundsSettings() DrawDebugBoundsColoredSettings

DefaultDrawDebugBoundsSettings returns the default settings for drawing the debug bounds for a nodegraph.

type DrawSprite3dSettings added in v0.15.0

type DrawSprite3dSettings struct {
	// The image to render
	Image *ebiten.Image
	// How much to offset the depth - useful if you want the object to appear at a position,
	// but in front of or behind other objects. Negative is towards the camera, positive is away.
	// The offset ranges from 0 to 1.
	DepthOffset   float32
	WorldPosition Vector // The position of the sprite in 3D space
}

type DynamicRenderSettings added in v0.15.0

type DynamicRenderSettings struct {
	Model *Model // The model to be cloned for usage

	Position Vector  // The position to render the Model at. Ignored if Transform is set.
	Scale    Vector  // The scale to render the Model at. Ignored if Transform is set.
	Rotation Matrix4 // The rotation to render the Model with. Ignored if Transform is set.

	Transform Matrix4 // A transform to use for rendering; this is used if it is non-zero.

	Color Color // The color to render the Model.
	// contains filtered or unexported fields
}

type FinishMode added in v0.10.0

type FinishMode int
const (
	FinishModeLoop     FinishMode = iota // Loop on animation completion
	FinishModePingPong                   // Reverse on animation completion; if this is the case, the OnFinish() callback is called after two loops (one reversal)
	FinishModeStop                       // Stop on animation completion
)

type FloatRange added in v0.13.0

type FloatRange struct {
	Min, Max float64
}

func NewFloatRange added in v0.13.0

func NewFloatRange() FloatRange

func (*FloatRange) Set added in v0.13.0

func (ran *FloatRange) Set(min, max float64)

func (FloatRange) Value added in v0.13.0

func (ran FloatRange) Value() float64

type FogMode

type FogMode int

type GLTFLoadOptions

type GLTFLoadOptions struct {
	// Width and height of loaded Cameras. Defaults to -1 each, which will then instead load the size from the camera's resolution as exported in the GLTF file;
	// if the camera resolution isn't set there, cameras will load with a 1920x1080 camera size.
	CameraWidth, CameraHeight int
	CameraDepth               bool // If cameras should render depth or not
	DefaultToAutoTransparency bool // If DefaultToAutoTransparency is true, then opaque materials become Auto transparent materials in Tetra3D.
	// DependentLibraryResolver is a function that takes a relative path (string) to the blend file representing the dependent Library that the loading
	// Library requires. This function should return a reference to the dependent Library; if it returns nil, the linked objects from the dependent Library
	// will not be instantiated in the loading Library.
	// An example would be loading a level (level.gltf) composed of assets from another file (a GLTF file exported from assets.blend, which is a directory up).
	// In this example, loading level.gltf would require the dependent library, found in assets.gltf. Loading level.gltf will refer to objects linked from the assets
	// blend file, known as "../assets.blend".
	// You could then simply load the assets library first and then code the DependentLibraryResolver function to take the assets library, or code the
	// function to use the path to load the library on demand. You could then store the loaded result as necessary if multiple levels use this assets Library.
	DependentLibraryResolver func(blendPath string) *Library
	LoadExternalTextures     bool // Whether any external textures should automatically be loaded if you load a GLTF file using LoadGLTFFile(). Defaults to true.

	// If top-level objects in collections should be renamed according to their instance objects.
	RenameCollectionObjects bool
	// contains filtered or unexported fields
}

func DefaultGLTFLoadOptions

func DefaultGLTFLoadOptions() *GLTFLoadOptions

DefaultGLTFLoadOptions creates an instance of GLTFLoadOptions with some sensible defaults.

type Grid added in v0.10.0

type Grid struct {
	*Node
}

Grid represents a collection of points and the connections between them. A Grid can be used for pathfinding or simply for connecting points in space (like for a world map in a level-based game, for example).

func NewGrid added in v0.10.0

func NewGrid(name string) *Grid

NewGrid creates a new Grid.

func (*Grid) AddChildren added in v0.10.0

func (grid *Grid) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*Grid) Center added in v0.10.0

func (grid *Grid) Center() Vector

Center returns the center point of the Grid, given the positions of its GridPoints.

func (*Grid) Clone added in v0.10.0

func (grid *Grid) Clone() INode

Clone creates a clone of this GridPoint.

func (*Grid) ClosestGridPoint added in v0.15.0

func (grid *Grid) ClosestGridPoint(position Vector) *GridPoint

ClosestGridPoint returns the nearest grid point to the given world position.

func (*Grid) ClosestPositionOnGrid added in v0.15.0

func (grid *Grid) ClosestPositionOnGrid(position Vector) Vector

ClosestPositionOnGrid returns the nearest world position on the Grid to the given world position. This position can be directly on a GridPoint, or on a connection between GridPoints.

func (*Grid) Combine added in v0.10.0

func (grid *Grid) Combine(others ...*Grid)

Combine combines the Grid with the other Grids provided. This reparents the other' Grid's GridPoints (and other children) to be under the calling Grid's. If two GridPoints share the same position, they will be merged together. After combining a Grid with others, the other Grids will automatically be unparented from the scene nodegraph tree (as their GridPoints will have been absorbed).

func (*Grid) Dimensions added in v0.10.0

func (grid *Grid) Dimensions() Dimensions

Dimensions returns a Dimensions struct, indicating the overall "spread" of the GridPoints composing the Grid.

func (*Grid) DisconnectAllPoints added in v0.14.0

func (grid *Grid) DisconnectAllPoints()

DisconnectAllPoints disconnects all points from each other in the Grid.

func (*Grid) FirstPoint added in v0.10.0

func (grid *Grid) FirstPoint() *GridPoint

FirstPoint returns the first point out of the Grid's GridPoints. If the Grid has no GridPoints, then it will return nil.

func (*Grid) ForEachPoint added in v0.14.0

func (grid *Grid) ForEachPoint(forEach func(gridPoint *GridPoint))

ForEachPoint returns a slice of the children nodes that constitute this Grid's GridPoints.

func (*Grid) FurthestGridPoint added in v0.11.0

func (grid *Grid) FurthestGridPoint(position Vector) *GridPoint

FurthestGridPoint returns the furthest grid point to the given world position.

func (*Grid) HopCounts added in v0.14.0

func (grid *Grid) HopCounts(from Vector, targetPositions ...Vector) []HopCount

HopCounts returns the number of hops from the closest grid point to the starting position (from) to the closest grid points to all other provided positions.

func (*Grid) Index added in v0.11.2

func (grid *Grid) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*Grid) LastPoint added in v0.10.0

func (grid *Grid) LastPoint() *GridPoint

LastPoint returns the last point out of the Grid's GridPoints. If the Grid has no GridPoints, then it will return nil.

func (*Grid) MergeDuplicatePoints added in v0.15.0

func (grid *Grid) MergeDuplicatePoints(margin float64)

func (*Grid) Points added in v0.10.0

func (grid *Grid) Points() []*GridPoint

Points returns a slice of the children nodes that constitute this Grid's GridPoints.

func (*Grid) RandomPoint added in v0.10.0

func (grid *Grid) RandomPoint() *GridPoint

RandomPoint returns a random grid point in the grid.

func (*Grid) Type added in v0.10.0

func (grid *Grid) Type() NodeType

Type returns the NodeType for this object.

func (*Grid) Unparent added in v0.10.0

func (grid *Grid) Unparent()

Unparent unparents the Model from its parent, removing it from the scenegraph.

type GridConnection added in v0.15.0

type GridConnection struct {
	To       *GridPoint
	Passable bool    // Whether the connection should be considered as passable when performing pathfinding.
	Cost     float64 // The cost of the jump, from one grid point to another. Defaults to 0.
	// contains filtered or unexported fields
}

A GridConnection represents a one-way connection from one GridPoint to another.

func (*GridConnection) Clone added in v0.15.0

func (c *GridConnection) Clone() *GridConnection

Clone the GridConnection.

type GridPath added in v0.10.0

type GridPath struct {
	GridPoints []Vector
}

GridPath represents a sequence of grid points, used to traverse a path.

func (*GridPath) DebugDraw added in v0.14.0

func (gp *GridPath) DebugDraw(screen *ebiten.Image, camera *Camera, color Color)

func (*GridPath) HopCount added in v0.15.0

func (gp *GridPath) HopCount() int

HopCount returns the number of hops in the path (i.e. the number of nodes - 1).

func (*GridPath) Length added in v0.14.0

func (gp *GridPath) Length() float64

Length returns the length of the overall path.

func (*GridPath) Points added in v0.10.0

func (gp *GridPath) Points() []Vector

Points returns the points of the GridPath in a slice.

type GridPoint added in v0.10.0

type GridPoint struct {
	*Node
	Connections []*GridConnection
	// contains filtered or unexported fields
}

GridPoint represents a point on a Grid, used for pathfinding or connecting points in space. GridPoints are parented to a Grid and the connections are created seperate from their positions, which means you can move GridPoints freely after creation. Note that GridPoints consider themselves to be in the same Grid only if they have the same direct parent (being the Grid).

func NewGridPoint added in v0.10.0

func NewGridPoint(name string) *GridPoint

NewGridPoint creates a new GridPoint.

func NewGridPointFromNode added in v0.15.0

func NewGridPointFromNode(node *Node) *GridPoint

NewGridPoint creates a new GridPoint from an existing Node.

func (*GridPoint) AddChildren added in v0.10.0

func (point *GridPoint) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*GridPoint) Clone added in v0.10.0

func (point *GridPoint) Clone() INode

Clone clones the given GridPoint.

func (*GridPoint) Connect added in v0.10.0

func (point *GridPoint) Connect(other *GridPoint) (aToB, bToA *GridConnection)

Connect connects the GridPoint to the given other GridPoint.

func (*GridPoint) Connection added in v0.15.0

func (point *GridPoint) Connection(other *GridPoint) *GridConnection

Connection returns the GridConnection from one GridPoint to another. If they aren't connected, this function will return nil. Note that a connection between GridPoints goes both ways (so there are two connections between two GridPoints - one from either direction).

func (*GridPoint) Disconnect added in v0.10.0

func (point *GridPoint) Disconnect(other *GridPoint)

Disconnect disconnects the GridPoint from the given other GridPoint.

func (*GridPoint) DisconnectAll added in v0.14.0

func (point *GridPoint) DisconnectAll()

DisconnectAll disconnects the GridPoint from all other GridPoints.

func (*GridPoint) Index added in v0.11.2

func (point *GridPoint) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*GridPoint) IsConnected added in v0.10.0

func (point *GridPoint) IsConnected(other *GridPoint) bool

IsConnected returns if the provided GridPoint is connected to the given other GridPoint.

func (*GridPoint) IsOnSameGrid added in v0.10.0

func (point *GridPoint) IsOnSameGrid(other *GridPoint) bool

IsOnSameGrid returns if the grid point is on the same grid as the other given GridPoint.

func (*GridPoint) PathTo added in v0.10.0

func (point *GridPoint) PathTo(goal *GridPoint) *GridPath

PathTo creates a path going from the GridPoint to the given other GridPoint. The path generated should be the shortest-possible route, taking into account both the cumulative lengths (in units) and costs of individual hops. If a path is not possible from the starting point to the end point, then PathTo will return nil.

func (*GridPoint) Type added in v0.10.0

func (point *GridPoint) Type() NodeType

Type returns the NodeType for this object.

func (*GridPoint) Unparent added in v0.10.0

func (point *GridPoint) Unparent()

Unparent unparents the Model from its parent, removing it from the scenegraph.

type HopCount added in v0.14.0

type HopCount struct {
	Start       *GridPoint // The start of the path
	Destination *GridPoint // The end of the path
	HopCount    int        // How many hops it takes to get there (i.e. length of the path between the two points minus one)
}

HopCount indicates an instances of how many hops it takes to get to the specified GridPoint from the starting GridPoint.

type IBoundingObject added in v0.11.0

type IBoundingObject interface {
	INode
	// Colliding returns true if the BoundingObject is intersecting the other BoundingObject.
	Colliding(other IBoundingObject) bool
	// Collision returns a Collision if the BoundingObject is intersecting another BoundingObject. If
	// no intersection is reported, Collision returns nil.
	Collision(other IBoundingObject) *Collision

	// CollisionTest performs a collision test using the provided collision test settings structure.
	// As a nicety, CollisionTest also returns a distance-sorted slice of all of the Collisions (but you should rather
	// handle collisions with intent using the OnCollision function of the CollisionTestSettings struct).
	// The returned Collisions slice will be sorted in order of distance. If no Collisions occurred, it will return an empty slice.
	CollisionTest(settings CollisionTestSettings) []*Collision
}

IBoundingObject represents a Node type that can be tested for collision. The exposed functions are essentially just concerning whether an object that implements IBoundingObject is colliding with another IBoundingObject, and if so, by how much.

type ILight added in v0.10.0

type ILight interface {
	INode

	Light(meshPart *MeshPart, model *Model, targetColors []Color, onlyVisible bool) // Light lights the triangles in the MeshPart, storing the result in the targetColors
	// color buffer. If onlyVisible is true, only the visible vertices will be lit; if it's false, they will all be lit.
	IsOn() bool    // isOn is simply used tfo tell if a "generic" Light is on or not.
	SetOn(on bool) // SetOn sets whether the light is on or not

	Color() Color
	SetColor(c Color)
	Energy() float32
	SetEnergy(energy float32)
	// contains filtered or unexported methods
}

ILight represents an interface that is fulfilled by an object that emits light, returning the color a vertex should be given that Vertex and its model matrix.

type INode

type INode interface {
	// Name returns the object's name.
	Name() string
	// ID returns the object's unique ID.
	ID() uint64
	// SetName sets the object's name.
	SetName(name string)
	// Clone returns a clone of the specified INode implementer.
	Clone() INode
	// SetData sets user-customizeable data that could be usefully stored on this node.
	SetData(data interface{})
	// Data returns a pointer to user-customizeable data that could be usefully stored on this node.
	Data() interface{}
	// Type returns the NodeType for this object.
	Type() NodeType

	// Library returns the source Library from which this Node was instantiated. If it was created through code, this will be nil.
	Library() *Library

	// Parent returns the Node's parent. If the Node has no parent, this will return nil.
	Parent() INode
	// Unparent unparents the Node from its parent, removing it from the scenegraph.
	Unparent()
	// Scene looks for the Node's parents recursively to return what scene it exists in.
	// If the node is not within a tree (i.e. unparented), this will return nil.
	Scene() *Scene
	// Root returns the root node in this tree by recursively traversing this node's hierarchy of
	// parents upwards.
	Root() INode

	// ReindexChild moves the child in the calling Node's children slice to the specified newPosition.
	// The function returns the old index where the child Node was, or -1 if it wasn't a child of the calling Node.
	// The newPosition is clamped to the size of the node's children slice.
	ReindexChild(child INode, newPosition int) int

	// Index returns the index of the Node in its parent's children list.
	// If the node doesn't have a parent, its index will be -1.
	Index() int

	// Children() returns the Node's children as an INode.
	Children() []INode

	// SearchTree() returns a NodeFilter to search the given Node's hierarchical tree.
	SearchTree() *NodeFilter

	// AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph
	// hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.
	AddChildren(...INode)
	// RemoveChildren removes the provided children from this object.
	RemoveChildren(...INode)

	// ClearLocalTransform clears the local transform properties (position, scale, and rotation) for the Node, reverting it to essentially an
	// identity matrix (0, 0, 0 for position, 1, 1, 1 for scale, and an identity Matrix4 for rotation, indicating no rotation).
	// This can be useful because by default, when you parent one Node to another, the local transform properties (position,
	// scale, and rotation) are altered to keep the object in the same absolute location, even though the origin changes.
	ClearLocalTransform()

	// ResetWorldTransform resets the local transform properties (position, scale, and rotation) for the Node to the original transform when
	// the Node was first created / cloned / instantiated in the Scene.
	ResetWorldTransform()

	// ResetWorldPosition resets the Node's local position to the value the Node had when
	// it was first instantiated in the Scene or cloned.
	ResetWorldPosition()

	// ResetWorldScale resets the Node's local scale to the value the Node had when
	// it was first instantiated in the Scene or cloned.
	ResetWorldScale()

	// ResetWorldRotation resets the Node's local rotation to the value the Node had when
	// it was first instantiated in the Scene or cloned.
	ResetWorldRotation()

	// SetWorldTransform sets the Node's global (world) transform to the full 4x4 transformation matrix provided.
	SetWorldTransform(transform Matrix4)

	// LocalRotation returns the object's local rotation Matrix4.
	LocalRotation() Matrix4
	// SetLocalRotation sets the object's local rotation Matrix4 (relative to any parent).
	SetLocalRotation(rotation Matrix4)

	// LocalPosition returns the object's local position as a Vector.
	LocalPosition() Vector
	// SetLocalPosition sets the object's local position (position relative to its parent). If this object has no parent, the position should be
	// relative to world origin (0, 0, 0).
	SetLocalPositionVec(position Vector)
	// SetLocalPosition sets the object's local position (position relative to its parent). If this object has no parent, the position should be
	// relative to world origin (0, 0, 0).
	SetLocalPosition(x, y, z float64)

	// LocalScale returns the object's local scale (scale relative to its parent). If this object has no parent, the scale will be absolute.
	LocalScale() Vector
	// SetLocalScale sets the object's local scale (scale relative to its parent). If this object has no parent, the scale would be absolute.
	// scale should be a 3D vector (i.e. X, Y, and Z components).
	SetLocalScaleVec(scale Vector)
	SetLocalScale(w, h, d float64)

	// WorldRotation returns an absolute rotation Matrix4 representing the object's rotation.
	WorldRotation() Matrix4
	// SetWorldRotation sets an object's global, world rotation to the provided rotation Matrix4.
	SetWorldRotation(rotation Matrix4)
	// WorldPosition returns the node's world position, taking into account its parenting hierarchy.
	WorldPosition() Vector
	// SetWorldPositionVec sets the world position of the given object using the provided position vector.
	// Note that this isn't as performant as setting the position locally.
	SetWorldPositionVec(position Vector)
	// SetWorldPosition sets the world position of the given object using the provided position arguments.
	// Note that this isn't as performant as setting the position locally.
	SetWorldPosition(x, y, z float64)
	// SetWorldX sets the x component of the Node's world position.
	SetWorldX(x float64)
	// SetWorldY sets the y component of the Node's world position.
	SetWorldY(x float64)
	// SetWorldZ sets the z component of the Node's world position.
	SetWorldZ(x float64)
	// WorldScale returns the object's absolute world scale as a 3D vector (i.e. X, Y, and Z components).
	WorldScale() Vector
	// SetWorldScaleVec sets the object's absolute world scale. scale should be a 3D vector (i.e. X, Y, and Z components).
	SetWorldScaleVec(scale Vector)

	// Move moves a Node in local space by the x, y, and z values provided.
	Move(x, y, z float64)
	// MoveVec moves a Node in local space using the vector provided.
	MoveVec(moveVec Vector)
	// Rotate rotates a Node on its local orientation on a vector composed of the given x, y, and z values, by the angle provided in radians.
	Rotate(x, y, z, angle float64)
	// RotateVec rotates a Node on its local orientation on the given vector, by the angle provided in radians.
	RotateVec(vec Vector, angle float64)
	// Grow scales the object additively (i.e. calling Node.Grow(1, 0, 0) will scale it +1 on the X-axis).
	Grow(x, y, z float64)
	// GrowVec scales the object additively (i.e. calling Node.Grow(1, 0, 0) will scale it +1 on the X-axis).
	GrowVec(vec Vector)

	// Transform returns a Matrix4 indicating the global position, rotation, and scale of the object, transforming it by any parents'.
	// If there's no change between the previous Transform() call and this one, Transform() will return a cached version of the
	// transform for efficiency.
	Transform() Matrix4

	// Visible returns whether the Object is visible.
	Visible() bool
	// SetVisible sets the object's visibility. If recursive is true, all recursive children of this Node will have their visibility set the same way.
	SetVisible(visible, recursive bool)

	// Get searches a node's hierarchy using a string to find a specified node. The path is in the format of names of nodes, separated by forward
	// slashes ('/'), and is relative to the node you use to call Get. As an example of Get, if you had a cup parented to a desk, which was
	// parented to a room, that was finally parented to the root of the scene, it would be found at "Room/Desk/Cup". Note also that you can use "../" to
	// "go up one" in the hierarchy (so cup.Get("../") would return the Desk node).
	// Since Get uses forward slashes as path separation, it would be good to avoid using forward slashes in your Node names. Also note that Get()
	// trims the extra spaces from the beginning and end of Node Names, so avoid using spaces at the beginning or end of your Nodes' names.
	Get(path string) INode

	// FindNode searches a node's hierarchy using a string to find the specified Node.
	FindNode(nodeName string) INode

	// HierarchyAsString returns a string displaying the hierarchy of this Node, and all recursive children.
	// This is a useful function to debug the layout of a node tree, for example.
	HierarchyAsString() string

	// Path returns a string indicating the hierarchical path to get this Node from the root. The path returned will be absolute, such that
	// passing it to Get() called on the scene root node will return this node. The path returned will not contain the root node's name ("Root").
	Path() string

	// Properties returns this object's game Properties struct.
	Properties() Properties

	// IsBone returns if the Node is a "bone" (a node that was a part of an armature and so can play animations back to influence a skinned mesh).
	IsBone() bool

	// AnimationPlayer returns the object's animation player - every object has an AnimationPlayer by default.
	AnimationPlayer() *AnimationPlayer

	// Sector returns the Sector this Node is in.
	Sector() *Sector

	SetSectorType(sectorType SectorType)
	SectorType() SectorType

	// DistanceTo returns the distance between the given Nodes' centers.
	// Quick syntactic sugar for Node.WorldPosition().Distance(otherNode.WorldPosition()).
	DistanceTo(otherNode INode) float64

	// DistanceSquared returns the squared distance between the given Nodes' centers.
	// Quick syntactic sugar for Node.WorldPosition().DistanceSquared(otherNode.WorldPosition()).
	DistanceSquaredTo(otherNode INode) float64
	// contains filtered or unexported methods
}

INode represents an object that exists in 3D space and can be positioned relative to an origin point. By default, this origin point is {0, 0, 0} (or world origin), but Nodes can be parented to other Nodes to change this origin (making their movements relative and their transforms successive). Models and Cameras are two examples of objects that fully implement the INode interface by means of embedding Node.

type IPath added in v0.10.0

type IPath interface {
	// Length returns the length of the overall path.
	Length() float64
	// Points returns the points of the IPath in a slice.
	Points() []Vector
	HopCount() int // HopCount returns the number of hops in the path.
	// contains filtered or unexported methods
}

type IntRange added in v0.13.0

type IntRange struct {
	Min, Max int
}

func NewIntRange added in v0.13.0

func NewIntRange() IntRange

func (*IntRange) Set added in v0.13.0

func (ran *IntRange) Set(min, max int)

func (IntRange) Value added in v0.13.0

func (ran IntRange) Value() int

type Intersection added in v0.8.1

type Intersection struct {
	StartingPoint Vector    // The starting point for the initiating object in the intersection in world space; either the center of the object for sphere / aabb, the center of the closest point for capsules, or the triangle position for triangles.
	ContactPoint  Vector    // The contact point for the intersection on the second, collided object in world space (i.e. the point of collision on the triangle in a Sphere>Triangles test).
	MTV           Vector    // MTV represents the minimum translation vector to remove the calling object from the intersecting object.
	Triangle      *Triangle // Triangle represents the triangle that was intersected in intersection tests that involve triangle meshes; if no triangle mesh was tested against, then this will be nil.
	Normal        Vector
}

func (*Intersection) SlideAgainstNormal added in v0.10.0

func (intersection *Intersection) SlideAgainstNormal(movementVec Vector) Vector

SlideAgainstNormal takes an input vector and alters it to slide against the intersection's returned normal.

func (*Intersection) Slope added in v0.9.1

func (intersection *Intersection) Slope() float64

Slope returns the slope of the intersection's normal, in radians. This ranges from 0 (straight up) to pi (straight down).

type Keyframe

type Keyframe struct {
	Time float64
	Data Data
}

Keyframe represents a single keyframe in an animation for an AnimationTrack.

type Library

type Library struct {
	Scenes        []*Scene              // A slice of Scenes
	ExportedScene *Scene                // The scene that was open when the library was exported from the modeler
	Meshes        map[string]*Mesh      // A Map of Meshes to their names
	Animations    map[string]*Animation // A Map of Animations to their names
	Materials     map[string]*Material  // A Map of Materials to their names
	Worlds        map[string]*World     // A Map of Worlds to their names
}

Library represents a collection of Scenes, Meshes, Animations, etc., as loaded from an intermediary file format (.dae or .gltf / .glb).

func LoadDAEData

func LoadDAEData(data []byte, options *DaeLoadOptions) (*Library, error)

LoadDAEData takes a []byte consisting of the contents of a DAE file, and returns a *Library populated with the .dae file's objects and meshes. Animations will not be loaded from DAE files, as DAE exports through Blender only support one animation per object (so it's generally advised to use the GLTF or GLB format instead). Cameras exported in the DAE file will be turned into simple Nodes in Tetra3D, as there's not enough information to instantiate a tetra3d.Camera. If the call couldn't complete for any reason, like due to a malformed DAE file, it will return an error.

func LoadDAEFile

func LoadDAEFile(path string, options *DaeLoadOptions) (*Library, error)

LoadDAEFile takes a filepath to a .dae model file, and returns a *Library populated with the .dae file's objects and meshes. Animations will not be loaded from DAE files, as DAE exports through Blender only support one animation per object (so it's generally advised to use the GLTF or GLB format instead). Cameras exported in the DAE file will be turned into simple Nodes in Tetra3D, as there's not enough information to instantiate a tetra3d.Camera. If the call couldn't complete for any reason, like due to a malformed DAE file, it will return an error.

func LoadGLTFData

func LoadGLTFData(data io.Reader, gltfLoadOptions *GLTFLoadOptions) (*Library, error)

LoadGLTFData loads a .gltf or .glb file from the byte data given, using a provided GLTFLoadOptions struct to alter how the file is loaded. Passing nil for loadOptions will load the file using default load options. Unlike with DAE files, Animations (including armature-based animations) and Cameras (assuming they are exported in the GLTF file) will be parsed properly. LoadGLTFFile will not work by default with external byte information buffers (i.e. .gltf and .glb file pairs) as the buffer is referenced in .gltf as just a filename. To handle this properly, load the .gltf file using LoadGLTFFile(). LoadGLTFFile will return a Library, and an error if the process fails.

func LoadGLTFFileSystem added in v0.15.0

func LoadGLTFFileSystem(fileSystem fs.FS, filename string, gltfLoadOptions *GLTFLoadOptions) (*Library, error)

LoadGLTFFileSystem loads a .gltf or .glb file from the file system given using the filename provided. The provided GLTFLoadOptions struct alters how the file is loaded. Passing nil for gltfLoadOptions will load the file using default load options. LoadGLTFFileSystem properly handles .gltf + .bin file pairs. LoadGLTFFileSystem will return a Library, and an error if the process fails.

func NewLibrary

func NewLibrary() *Library

NewLibrary creates a new Library.

func (*Library) AddScene

func (lib *Library) AddScene(sceneName string) *Scene

func (*Library) FindNode added in v0.8.1

func (lib *Library) FindNode(objectName string) INode

FindNode allows you to find a node by name by searching through each of a Library's scenes. If the Node with the given name isn't found, FindNode will return nil.

func (*Library) FindScene

func (lib *Library) FindScene(name string) *Scene

FindScene searches all scenes in a Library to find the one with the provided name. If a scene with the given name isn't found, FindScene will return nil.

type LightGroup added in v0.10.0

type LightGroup struct {
	Lights []ILight // The collection of lights present in the LightGroup.
	Active bool     // If the LightGroup is active or not; when a Model's LightGroup is inactive, Models will fallback to the lights present under the Scene's root.
}

LightGroup represents a grouping of lights. This is used on Models to control which lights are used to light them.

func NewLightGroup added in v0.10.0

func NewLightGroup(lights ...ILight) *LightGroup

NewLightGroup creates a new LightGroup.

func (*LightGroup) Add added in v0.10.0

func (lg *LightGroup) Add(lights ...ILight)

Add adds the passed ILights to the LightGroup.

func (*LightGroup) Clone added in v0.10.0

func (lg *LightGroup) Clone() *LightGroup

Clone clones the LightGroup.

type Marker added in v0.8.1

type Marker struct {
	Time float64 // Time of the marker in seconds in the Animation.
	Name string  // Name of the marker.
}

Marker represents a tag as placed in an Animation in a 3D modeler.

type Material

type Material struct {
	Name              string        // Name is the name of the Material.
	Color             Color         // The overall color of the Material.
	Texture           *ebiten.Image // The texture applied to the Material.
	TexturePath       string        // The path to the texture, if it was not packed into the exporter.
	TextureFilterMode ebiten.Filter // Texture filtering mode

	BackfaceCulling  bool         // If backface culling is enabled (which it is by default), faces turned away from the camera aren't rendered.
	TriangleSortMode int          // TriangleSortMode influences how triangles with this Material are sorted.
	Shadeless        bool         // If the material should be shadeless (unlit) or not
	Fogless          bool         // If the material should be fogless or not
	Blend            ebiten.Blend // Blend mode to use when rendering the material (i.e. additive, multiplicative, etc)
	BillboardMode    int          // Billboard mode
	Visible          bool         // Whether the material is visible or not

	// FragmentShaderOn is an easy boolean toggle to control whether the shader is activated or not (it defaults to on).
	FragmentShaderOn bool
	// FragmentShaderOptions allows you to customize the custom fragment shader with uniforms or images.
	// By default, it's an empty DrawTrianglesShaderOptions struct.
	// Note that the first image slot is reserved for the color texture associated with the Material.
	// The second slot is reserved for a depth texture (primarily the intermediate texture used to "cut" a
	// rendered model).
	// If you want a custom fragment shader that already has fog and depth-testing, use Extend3DBaseShader() to
	// extend your custom fragment shader from Tetra3D's base 3D shader.
	FragmentShaderOptions *ebiten.DrawTrianglesShaderOptions

	// If a material is tagged as transparent, it's rendered in a separate render pass.
	// Objects with transparent materials don't render to the depth texture and are sorted and rendered back-to-front, AFTER
	// all non-transparent materials.
	TransparencyMode int

	CustomDepthOffsetOn    bool    // Whether custom depth offset is on or not.
	CustomDepthOffsetValue float64 // How many world units to offset the depth of the material by.
	LightingMode           int     // How materials are lit

	// CustomDepthFunction is a customizeable function that takes the depth value of each vertex of a rendered MeshPart and
	// transforms it, returning a different value.
	// A good use for this would be to render sprites on billboarded planes with a higher depth, thereby fixing them
	// "cutting" into geometry that's further back.
	// The default value for CustomDepthFunction is nil.
	CustomDepthFunction func(originalDepth float64) float64
	// contains filtered or unexported fields
}

func NewMaterial

func NewMaterial(name string) *Material

NewMaterial creates a new Material with the name given.

func (*Material) Clone

func (material *Material) Clone() *Material

Clone creates a clone of the specified Material. Note that Clone() cannot clone the Material's fragment shader or shader options.

func (*Material) DisposeShader added in v0.8.1

func (material *Material) DisposeShader()

DisposeShader disposes the custom fragment Shader for the Material (assuming it has one). If it does not have a Shader, nothing happens.

func (*Material) Library added in v0.8.1

func (material *Material) Library() *Library

Library returns the Library from which this Material was loaded. If it was created through code, this function will return nil.

func (*Material) Properties added in v0.11.0

func (material *Material) Properties() Properties

Properties returns this Material's game Properties struct.

func (*Material) SetShader added in v0.8.1

func (material *Material) SetShader(shader *ebiten.Shader)

SetShader sets an already-compiled custom Kage shader to the Material. By default, a custom shader will render on top of everything and with no fog. Lighting will also be missing, but that's included in the Model's vertex color. If you want to extend the base 3D shader, use tetra3d.ExtendBase3DShader(). Note that custom shaders require usage of pixel-unit Kage shaders.

func (*Material) SetShaderText added in v0.14.0

func (material *Material) SetShaderText(src []byte) (*ebiten.Shader, error)

SetShaderText creates a new custom Kage fragment shader for the Material if provided the shader's source code as a []byte. This custom shader would be used to render the mesh utilizing the material after rendering to the depth texture, but before compositing the finished render to the screen after fog. If the shader is nil, the Material will render using the default Tetra3D render setup (e.g. texture, UV values, vertex colors, and vertex lighting). SetShader will return the Shader, and an error if the Shader failed to compile. Note that custom shaders require usage of pixel-unit Kage shaders.

func (*Material) Shader added in v0.8.1

func (material *Material) Shader() *ebiten.Shader

Shader returns the custom Kage fragment shader for the Material.

func (*Material) String added in v0.12.0

func (material *Material) String() string

type Matrix4

type Matrix4 [4][4]float64

Matrix4 represents a 4x4 matrix for translation, scale, and rotation. A Matrix4 in Tetra3D is row-major (i.e. the X axis is matrix[0]).

func NewEmptyMatrix4

func NewEmptyMatrix4() Matrix4

func NewLookAtMatrix

func NewLookAtMatrix(from, to, up Vector) Matrix4

NewLookAtMatrix generates a new Matrix4 to rotate an object to point towards another object. to is the target's world position, from is the world position of the object looking towards the target, and up is the upward vector ( usually +Y, or [0, 1, 0] ).

func NewMatrix4

func NewMatrix4() Matrix4

NewMatrix4 returns a new identity Matrix4. A Matrix4 in Tetra3D is row-major (i.e. the X axis for a rotation Matrix4 is matrix[0][0], matrix[0][1], matrix[0][2]).

func NewMatrix4Rotate

func NewMatrix4Rotate(x, y, z, angle float64) Matrix4

NewMatrix4Rotate returns a new Matrix4 designed to rotate by the angle given (in radians) along the axis given [x, y, z]. This rotation works as though you pierced the object utilizing the matrix through by the axis, and then rotated it counter-clockwise by the angle in radians.

func NewMatrix4RotateFromEuler added in v0.11.2

func NewMatrix4RotateFromEuler(euler Vector) Matrix4

NewMatrix4RotateFromEuler creates a rotation Matrix4 from the euler values contained within the Vector.

func NewMatrix4Scale

func NewMatrix4Scale(x, y, z float64) Matrix4

NewMatrix4Scale returns a new identity Matrix4, but with the scale components set as provided. 1, 1, 1 is the default.

func NewMatrix4Translate

func NewMatrix4Translate(x, y, z float64) Matrix4

NewMatrix4Scale returns a new identity Matrix4, but with the x, y, and z translation components set as provided.

func NewProjectionOrthographic

func NewProjectionOrthographic(near, far, right, left, top, bottom float64) Matrix4

NewProjectionOrthographic generates an orthographic frustum Matrix4. near and far are the near and far clipping plane. right, left, top, and bottom are the right, left, top, and bottom planes (usually 1 and -1 for right and left, and the aspect ratio of the window and negative for top and bottom). Generally, you won't need to use this directly.

func NewProjectionPerspective

func NewProjectionPerspective(fovy, near, far, viewWidth, viewHeight float64) Matrix4

NewProjectionPerspective generates a perspective frustum Matrix4. fovy is the vertical field of view in degrees, near and far are the near and far clipping plane, while viewWidth and viewHeight is the width and height of the backing texture / camera. Generally, you won't need to use this directly.

func (Matrix4) Add

func (matrix Matrix4) Add(other Matrix4) Matrix4

func (Matrix4) BlenderToTetra

func (matrix Matrix4) BlenderToTetra() Matrix4

BlenderToTetra returns a Matrix with the rows altered such that Blender's +Z is now Tetra's +Y and Blender's +Y is now Tetra's -Z.

func (*Matrix4) Clear

func (matrix *Matrix4) Clear()

func (Matrix4) Clone

func (matrix Matrix4) Clone() Matrix4

Clone clones the Matrix4, returning a new copy.

func (Matrix4) Column

func (matrix Matrix4) Column(columnIndex int) Vector

Column returns the indiced column from the Matrix4 as a Vector.

func (Matrix4) Columns

func (matrix Matrix4) Columns() [][]float64

Columns returns the Matrix4 as a slice of []float64, in column-major order (so it's transposed from the row-major default).

func (Matrix4) Decompose

func (matrix Matrix4) Decompose() (Vector, Vector, Matrix4)

Decompose decomposes the Matrix4 and returns three components - the position (a 3D Vector), scale (another 3D Vector), and rotation (a Matrix4) indicated by the Matrix4. Note that this is mainly used when loading a mesh from a 3D modeler - this being the case, it may not be the most precise, and negative scales are not supported.

func (Matrix4) Equals

func (matrix Matrix4) Equals(other Matrix4) bool

Equals returns true if the matrix equals the same values in the provided Other Matrix4.

func (Matrix4) Forward

func (matrix Matrix4) Forward() Vector

Forward returns the forward rotational component of the Matrix4. For an identity matrix, this would be [0, 0, 1], or +Z (towards camera).

func (Matrix4) HasValidRotation added in v0.9.1

func (matrix Matrix4) HasValidRotation() bool

HasValidRotation returns if the first three vectors in the Matrix are non-zero

func (*Matrix4) Index added in v0.8.1

func (matrix *Matrix4) Index(index int) float64

func (Matrix4) Inverted

func (matrix Matrix4) Inverted() Matrix4

Inverted returns an inverted version of the Matrix4. The ultimate sin; I'm just going to copy this code for inverting a 4x4 Matrix and call it a day. This code was obtained from https://stackoverflow.com/questions/1148309/inverting-a-4x4-matrix, and is like 200x faster than my old inversion code, whaaaaa

func (Matrix4) IsIdentity

func (matrix Matrix4) IsIdentity() bool

IsIdentity returns true if the matrix is an unmodified identity matrix.

func (Matrix4) IsZero

func (matrix Matrix4) IsZero() bool

IsZero returns true if the Matrix is zero'd out (all values are 0).

func (Matrix4) Lerp added in v0.12.0

func (mat Matrix4) Lerp(other Matrix4, percent float64) Matrix4

Lerp lerps a matrix to another, destination Matrix by the percent given. It does this by converting both Matrices to Quaternions, lerping them, then converting the result back to a Matrix4.

func (Matrix4) Mult

func (matrix Matrix4) Mult(other Matrix4) Matrix4

Mult multiplies a Matrix4 by another provided Matrix4 - this effectively combines them.

func (Matrix4) MultVec

func (matrix Matrix4) MultVec(vect Vector) Vector

MultVec multiplies the vector provided by the Matrix4, giving a vector that has been rotated, scaled, or translated as desired.

func (Matrix4) MultVecW

func (matrix Matrix4) MultVecW(vect Vector) Vector

MultVecW multiplies the vector provided by the Matrix4, including the fourth (W) component, giving a vector that has been rotated, scaled, or translated as desired.

func (Matrix4) Right

func (matrix Matrix4) Right() Vector

Right returns the right-facing rotational component of the Matrix4. For an identity matrix, this would be [1, 0, 0], or +X.

func (Matrix4) Rotated

func (matrix Matrix4) Rotated(x, y, z, angle float64) Matrix4

Rotated returns a clone of the Matrix4 rotated along the local axis by the angle given (in radians). This rotation works as though you pierced the object through by the axis, and then rotated it counter-clockwise by the angle in radians. The axis is relative to any existing rotation contained in the matrix.

func (Matrix4) Row

func (matrix Matrix4) Row(rowIndex int) Vector

Row returns the indiced row from the Matrix4 as a Vector.

func (Matrix4) ScaleByScalar

func (matrix Matrix4) ScaleByScalar(scalar float64) Matrix4

func (*Matrix4) Set added in v0.10.0

func (matrix *Matrix4) Set(other Matrix4)

Set allows you to set the Matrix4 to the same values as another Matrix4.

func (*Matrix4) SetColumn

func (matrix *Matrix4) SetColumn(columnIndex int, vec Vector)

SetColumn sets the Matrix4 with the column in columnIndex set to the 4D vector passed.

func (*Matrix4) SetRow

func (matrix *Matrix4) SetRow(rowIndex int, vec Vector)

SetRow sets the Matrix4 with the row in rowIndex set to the 4D vector passed.

func (Matrix4) String

func (matrix Matrix4) String() string

func (Matrix4) Sub added in v0.10.0

func (matrix Matrix4) Sub(other Matrix4) Matrix4

func (Matrix4) ToQuaternion added in v0.10.0

func (matrix Matrix4) ToQuaternion() Quaternion

ToQuaternion returns a Quaternion representative of the Matrix4's rotation (assuming it is just a purely rotational Matrix4).

func (Matrix4) Transposed

func (matrix Matrix4) Transposed() Matrix4

Transposed transposes a Matrix4, switching the Matrix from being Row Major to being Column Major. For orthonormalized Matrices (matrices that have rows that are normalized (having a length of 1), like rotation matrices), this is equivalent to inverting it.

func (Matrix4) Up

func (matrix Matrix4) Up() Vector

Up returns the upward rotational component of the Matrix4. For an identity matrix, this would be [0, 1, 0], or +Y.

type Mesh

type Mesh struct {
	Name   string // The name of the Mesh resource
	Unique bool   // If true, whenever a Mesh is used for a Model and the Model is cloned, the Mesh is cloned with it. Useful for things like sprites.

	MeshParts []*MeshPart // The various mesh parts (collections of triangles, rendered with a single material).
	Triangles []*Triangle // The various triangles composing the Mesh.

	VertexPositions []Vector
	VertexNormals   []Vector

	VertexUVs                []Vector
	VertexColors             [][]Color
	VertexActiveColorChannel []int       // VertexActiveColorChannel is the active vertex color used for coloring the vertex in the index given.
	VertexWeights            [][]float32 // TODO: Replace this with [][8]float32 (or however many the maximum is for GLTF)
	VertexBones              [][]uint16  // TODO: Replace this with [][8]uint16 (or however many the maximum number of bones affecting a single vertex is for GLTF)

	VertexColorChannelNames map[string]int // VertexColorChannelNames is a map allowing you to get the index of a mesh's vertex color channel by its name.
	Dimensions              Dimensions
	// contains filtered or unexported fields
}

Mesh represents a mesh that can be represented visually in different locations via Models. By default, a new Mesh has no MeshParts (so you would need to add one manually if you want to construct a Mesh via code).

func NewCubeMesh added in v0.11.0

func NewCubeMesh() *Mesh

NewCubeMesh creates a new 2x2x2 Cube Mesh and gives it a new material (suitably named "Cube").

func NewCylinderMesh added in v0.12.0

func NewCylinderMesh(sideCount int, radius float64, createCaps bool) *Mesh

NewCylinderMesh creates a new cylinder Mesh and gives it a new material (suitably named "Cylinder"). sideCount is how many sides the cylinder should have, while radius is the radius of the cylinder in world units. if createCaps is true, then the cylinder will have triangle caps.

func NewIcosphereMesh added in v0.11.0

func NewIcosphereMesh(detailLevel int) *Mesh

NewIcosphereMesh creates a new icosphere Mesh of the specified detail level. Note that the UVs are left at {0,0} because I'm lazy.

func NewMesh

func NewMesh(name string, verts ...VertexInfo) *Mesh

NewMesh takes a name and a slice of *Vertex instances, and returns a new Mesh. If you provide *Vertex instances, the number must be divisible by 3, or NewMesh will panic.

func NewPlaneMesh added in v0.11.0

func NewPlaneMesh(vertexCountX, vertexCountZ int) *Mesh

NewPlaneMesh creates a new 2x2 plane Mesh with a new material (suitably named "Plane"). vertexCountX and vertexCountY indicate how many vertices should be on the plane in the X and Z direction, respectively. The minimum number of vertices for either argument is 2. Code for this is taken from https://answers.unity.com/questions/1850185/mesh-triangles-not-filling-whole-space-2.html.

func NewPrismMesh added in v0.11.2

func NewPrismMesh() *Mesh

NewPrismMesh creates a new prism Mesh and gives it a new material (suitably named "Prism").

func (*Mesh) AddMeshPart added in v0.8.1

func (mesh *Mesh) AddMeshPart(material *Material, indices ...int) *MeshPart

AddMeshPart allows you to add a new MeshPart to the Mesh with the given Material (with a nil Material reference also being valid).

func (*Mesh) AddVertices added in v0.11.0

func (mesh *Mesh) AddVertices(verts ...VertexInfo)

func (*Mesh) AutoNormal added in v0.10.0

func (mesh *Mesh) AutoNormal()

AutoNormal automatically recalculates the normals for the triangles contained within the Mesh and sets the vertex normals for all triangles to the triangles' surface normal.

func (*Mesh) Clone

func (mesh *Mesh) Clone() *Mesh

Clone clones the Mesh, creating a new Mesh that has cloned MeshParts.

func (*Mesh) CombineVertexColors added in v0.10.0

func (mesh *Mesh) CombineVertexColors(targetChannel int, multiplicative bool, sourceChannels ...int)

CombineVertexColors allows you to combine vertex color channels together. The targetChannel is the channel that will hold the result, and multiplicative controls whether the combination is multiplicative (true) or additive (false). The sourceChannels ...int is the vertex color channel indices to combine together.

func (*Mesh) FindMeshPart added in v0.9.0

func (mesh *Mesh) FindMeshPart(materialName string) *MeshPart

FindMeshPart allows you to retrieve a MeshPart by its material's name. If no material with the provided name is given, the function returns nil.

func (*Mesh) GetVertexInfo added in v0.9.0

func (mesh *Mesh) GetVertexInfo(vertexIndex int) VertexInfo

GetVertexInfo returns a VertexInfo struct containing the vertex information for the vertex with the provided index.

func (*Mesh) Library added in v0.8.1

func (mesh *Mesh) Library() *Library

Library returns the Library from which this Mesh was loaded. If it was created through code, this function will return nil.

func (*Mesh) Materials added in v0.10.0

func (mesh *Mesh) Materials() []*Material

Materials returns a slice of the materials present in the Mesh's MeshParts.

func (*Mesh) Properties added in v0.11.0

func (mesh *Mesh) Properties() Properties

Properties returns this Mesh object's game Properties struct.

func (*Mesh) SelectVertices added in v0.9.0

func (mesh *Mesh) SelectVertices() *VertexSelection

SelectVertices generates a new vertex selection for the current Mesh.

func (*Mesh) SetActiveColorChannel added in v0.10.0

func (mesh *Mesh) SetActiveColorChannel(targetChannel int)

SetActiveColorChannel sets the active color channel for all vertices in the mesh to the specified channel index.

func (*Mesh) SetVertexColor

func (mesh *Mesh) SetVertexColor(targetChannel int, color Color)

SetVertexColor sets the specified vertex color for all vertices in the mesh for the target color channel.

func (*Mesh) UpdateBounds

func (mesh *Mesh) UpdateBounds()

UpdateBounds updates the mesh's dimensions; call this after manually changing vertex positions.

type MeshPart added in v0.8.1

type MeshPart struct {
	Mesh             *Mesh
	Material         *Material
	VertexIndexStart int
	VertexIndexEnd   int
	TriangleStart    int
	TriangleEnd      int
	// contains filtered or unexported fields
}

MeshPart represents a collection of vertices and triangles, which are all rendered at once, as a single part, with a single material. Depth testing is done between mesh parts or objects, so splitting an object up into different materials can be effective to help with depth sorting.

func NewMeshPart added in v0.8.1

func NewMeshPart(mesh *Mesh, material *Material) *MeshPart

NewMeshPart creates a new MeshPart that renders using the specified Material.

func (*MeshPart) AddTriangles added in v0.8.1

func (part *MeshPart) AddTriangles(indices ...int)

AddTriangles adds triangles to the MeshPart using the provided VertexInfo slice.

func (*MeshPart) ApplyMatrix added in v0.8.1

func (part *MeshPart) ApplyMatrix(matrix Matrix4)

ApplyMatrix applies a transformation matrix to the vertices referenced by the MeshPart.

func (*MeshPart) AssignToMesh added in v0.11.0

func (part *MeshPart) AssignToMesh(mesh *Mesh)

func (*MeshPart) Clone added in v0.8.1

func (part *MeshPart) Clone() *MeshPart

Clone clones the MeshPart, returning the copy.

func (*MeshPart) ForEachTri added in v0.11.0

func (part *MeshPart) ForEachTri(triFunc func(tri *Triangle))

func (*MeshPart) ForEachVertexIndex added in v0.11.0

func (part *MeshPart) ForEachVertexIndex(vertFunc func(vertIndex int), onlyVisible bool)

ForEachVertexIndex calls the provided function for each vertex index that the MeshPart uses. If onlyVisible is true, then only the visible vertices (vertices that are rendered; that aren't backface culled or offscreen) will be used with the provided function.

func (*MeshPart) TriangleCount added in v0.9.0

func (part *MeshPart) TriangleCount() int

TriangleCount returns the total number of triangles in the MeshPart, specifically.

func (*MeshPart) VertexIndexCount added in v0.11.0

func (part *MeshPart) VertexIndexCount() int

type ModVector added in v0.11.0

type ModVector struct {
	*Vector
}

ModVector represents a reference to a Vector, made to facilitate easy method-chaining and modifications on that Vector (as you don't need to re-assign the results of a chain of operations to the original variable to "save" the results). Note that a ModVector is not meant to be used to chain methods on a vector to pass directly into a function; you can just use the normal vector functions for that purpose. ModVectors are pointers, which are allocated to the heap. This being the case, they should be slower relative to normal Vectors, so use them only in non-performance-critical parts of your application.

func (ModVector) Add added in v0.11.0

func (ip ModVector) Add(other Vector) ModVector

Add adds the other Vector provided to the ModVector. This function returns the calling ModVector for method chaining.

func (ModVector) Ceil added in v0.15.0

func (ip ModVector) Ceil() ModVector

Ceil ceils the ModVector's components off, returning a new Vector. For example, Vector{0.1, 1.27, 3.33}.Modify().Ceil() will return Vector{1, 2, 4}. This function returns the calling ModVector for method chaining.

func (ModVector) Clamp added in v0.15.0

func (ip ModVector) Clamp(x, y, z float64) ModVector

Clamp clamps the Vector to the maximum values provided. This function returns the calling ModVector for method chaining.

func (ModVector) ClampAngle added in v0.15.0

func (ip ModVector) ClampAngle(baselineVec Vector, maxAngle float64) ModVector

ClampAngle clamps the Vector such that it doesn't exceed the angle specified (in radians). This function returns a normalized (unit) ModVector for method chaining.

func (ModVector) ClampMagnitude added in v0.11.0

func (ip ModVector) ClampMagnitude(maxMag float64) ModVector

ClampMagnitude clamps the overall magnitude of the Vector to the maximum magnitude specified. This function returns the calling ModVector for method chaining.

func (ModVector) ClampVec added in v0.15.0

func (ip ModVector) ClampVec(extents Vector) ModVector

ClampVec clamps the Vector to the maximum values in the Vector provided. This function returns the calling ModVector for method chaining.

func (ModVector) Clone added in v0.11.0

func (ip ModVector) Clone() ModVector

Clone returns a ModVector of a clone of its backing Vector. This function returns the calling ModVector for method chaining.

func (ModVector) Cross added in v0.11.0

func (ip ModVector) Cross(other Vector) ModVector

Cross performs a cross-product multiplication on the ModVector. This function returns the calling ModVector for method chaining.

func (ModVector) Divide added in v0.11.0

func (ip ModVector) Divide(scalar float64) ModVector

Divide divides a Vector by the given scalar (ignoring the W component). This function returns the calling ModVector for method chaining.

func (ModVector) Expand added in v0.11.0

func (ip ModVector) Expand(margin, min float64) ModVector

Expand expands the ModVector by the margin specified, in absolute units, if each component is over the minimum argument. To illustrate: Given a ModVector of {1, 0.1, -0.3}, ModVector.Expand(0.5, 0.2) would give you a ModVector of {1.5, 0.1, -0.8}. This function returns the calling ModVector for method chaining.

func (ModVector) Floor added in v0.15.0

func (ip ModVector) Floor() ModVector

Floor floors the ModVector's components off, returning a new Vector. For example, Vector{0.1, 1.27, 3.33}.Modify().Floor() will return Vector{0, 1, 3}. This function returns the calling ModVector for method chaining.

func (ModVector) Invert added in v0.11.0

func (ip ModVector) Invert() ModVector

Invert inverts all components of the calling ModVector. This function returns the calling ModVector for method chaining.

func (ModVector) Lerp added in v0.15.0

func (ip ModVector) Lerp(other Vector, percentage float64) ModVector

Lerp performs a linear interpolation between the starting ModVector and the provided other Vector, to the given percentage. This function returns the calling ModVector for method chaining.

func (ModVector) Mult added in v0.13.0

func (ip ModVector) Mult(other Vector) ModVector

Mult performs Hadamard (component-wise) multiplication with the Vector on the other Vector provided. This function returns the calling ModVector for method chaining.

func (ModVector) Rotate added in v0.11.0

func (ip ModVector) Rotate(x, y, z, angle float64) ModVector

RotateVec rotates the calling ModVector by an axis Vector composed of the x, y, and z components provided, by the angle provided (in radians). This function returns the calling ModVector for method chaining.

func (ModVector) RotateVec added in v0.11.0

func (ip ModVector) RotateVec(axis Vector, angle float64) ModVector

RotateVec rotates the calling ModVector by the axis Vector and angle provided (in radians). This function returns the calling ModVector for method chaining.

func (ModVector) Round added in v0.15.0

func (ip ModVector) Round(roundToUnits float64) ModVector

Round rounds off the ModVector's components to the given space in world units. For example, Vector{0.1, 1.27, 3.33}.Modify().Round(0.25) will return Vector{0, 1.25, 3.25}. This function returns the calling ModVector for method chaining.

func (ModVector) Scale added in v0.11.0

func (ip ModVector) Scale(scalar float64) ModVector

Scale scales the Vector by the scalar provided. This function returns the calling ModVector for method chaining.

func (ModVector) SetZero added in v0.11.0

func (ip ModVector) SetZero() ModVector

func (ModVector) Slerp added in v0.15.0

func (ip ModVector) Slerp(other Vector, percentage float64) ModVector

Slerp performs a spherical linear interpolation between the starting ModVector and the provided other Vector, to the given percentage. This function returns the calling ModVector for method chaining.

func (ModVector) String added in v0.11.0

func (ip ModVector) String() string

String converts the ModVector to a string. Because it's a ModVector, it's represented with a *.

func (ModVector) Sub added in v0.11.0

func (ip ModVector) Sub(other Vector) ModVector

Sub subtracts the other Vector from the calling ModVector. This function returns the calling ModVector for method chaining.

func (ModVector) SubMagnitude added in v0.12.1

func (ip ModVector) SubMagnitude(mag float64) ModVector

SubMagnitude subtacts the given magnitude from the Vector's. If the vector's magnitude is less than the given magnitude to subtract, a zero-length Vector will be returned. This function returns the calling ModVector for method chaining.

func (ModVector) Swizzle added in v0.11.0

func (ip ModVector) Swizzle(swizzleString string) ModVector

Swizzle swizzles the ModVector using the string provided. The string can be of length 3 ("xyz") or 4 ("xyzw"). The string should be composed of the axes of a vector, i.e. 'x', 'y', 'z', or 'w'. Example: `vec := Vector{1, 2, 3}.Swizzle("zxy") // Returns a Vector of {3, 1, 2}.` This function returns the calling ModVector for method chaining.

func (ModVector) ToVector added in v0.11.0

func (ip ModVector) ToVector() Vector

func (ModVector) Unit added in v0.11.0

func (ip ModVector) Unit() ModVector

Unit normalizes the ModVector (sets it to be of unit length). It does not alter the W component of the Vector. This function returns the calling ModVector for method chaining.

type Model

type Model struct {
	*Node
	Mesh           *Mesh
	FrustumCulling bool // Whether the Model is culled when it leaves the frustum.

	Color     Color // The overall multiplicative color of the Model.
	Shadeless bool  // Indicates if a Model is shadeless.

	DynamicBatchModels map[*MeshPart][]*Model // Models that are dynamically merged into this one.
	DynamicBatchOwner  *Model

	SkinRoot INode // The root node of the armature skinning this Model.

	// A LightGroup indicates if a Model should be lit by a specific group of Lights. This allows you to control the overall lighting of scenes more accurately.
	// If a Model has no LightGroup, the Model is lit by the lights present in the Scene.
	LightGroup *LightGroup

	// VertexTransformFunction is a function that runs on the world position of each vertex position rendered with the material.
	// It accepts the vertex position as an argument, along with the index of the vertex in the mesh.
	// One can use this to simply transform vertices of the mesh on CPU (note that this is, of course, not as performant as
	// a traditional GPU vertex shader, but is fine for simple / low-poly mesh transformations).
	// This function is run after skinning the vertex if the material belongs to a mesh that is skinned by an armature.
	// Note that the VertexTransformFunction must return the vector passed.
	VertexTransformFunction func(vertexPosition Vector, vertexIndex int) Vector

	// VertexClipFunction is a function that runs on the clipped result of each vertex position rendered with the material.
	// The function takes the vertex position along with the vertex index in the mesh.
	// This program runs after the vertex position is clipped to screen coordinates.
	// Note that the VertexClipFunction must return the vector passed.
	VertexClipFunction func(vertexPosition Vector, vertexIndex int) Vector

	// Automatic batching mode; when set and a Model changes parenting, it will be automatically batched as necessary according to
	// the AutoBatchMode set.
	AutoBatchMode int
	// contains filtered or unexported fields
}

Model represents a singular visual instantiation of a Mesh. A Mesh contains the vertex information (what to draw); a Model references the Mesh to draw it with a specific Position, Rotation, and/or Scale (where and how to draw).

func NewModel

func NewModel(name string, mesh *Mesh) *Model

NewModel creates a new Model (or instance) of the Mesh and Name provided. A Model represents a singular visual instantiation of a Mesh.

func (*Model) AddChildren

func (model *Model) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*Model) BakeAO added in v0.10.0

func (model *Model) BakeAO(bakeOptions *AOBakeOptions)

BakeAO bakes the ambient occlusion for a model to its vertex colors, using the baking options set in the provided AOBakeOptions struct. If a slice of models is passed in the OtherModels slice, then inter-object AO will also be baked. If nil is passed instead of bake options, a default AOBakeOptions struct will be created and used. The resulting vertex color will be mixed between whatever was originally there in that channel and the AO color where the color takes effect.

func (*Model) BakeLighting added in v0.10.0

func (model *Model) BakeLighting(targetChannel int, lights ...ILight)

BakeLighting bakes the colors for the provided lights into a Model's Mesh's vertex colors. Note that the baked lighting overwrites whatever vertex colors previously existed in the target channel (as otherwise, the colors could only get brighter with additive mixing, or only get darker with multiplicative mixing).

func (*Model) Clone

func (model *Model) Clone() INode

Clone creates a clone of the Model.

func (*Model) DynamicBatchAdd added in v0.9.0

func (model *Model) DynamicBatchAdd(meshPart *MeshPart, batchedModels ...*Model) error

DynamicBatchAdd adds the provided models to the calling Model's dynamic batch, rendering with the specified meshpart (which should be part of the calling Model, of course). Note that unlike StaticMerge(), DynamicBatchAdd works by simply rendering the batched models using the calling Model's first MeshPart's material. By dynamically batching models together, this allows us to not flush between rendering multiple Models, saving a lot of render time, particularly if rendering many low-poly, individual models that have very little variance (i.e. if they all share a single texture). Calling this turns the model into a dynamic batching owner, meaning that it will no longer render its own mesh (for simplicity). For more information, see this Wiki page on batching / merging: https://github.com/SolarLune/Tetra3d/wiki/Merging-and-Batching-Draw-Calls

func (*Model) DynamicBatchClear added in v0.15.0

func (model *Model) DynamicBatchClear()

DynamicBatchClear clears the model's dynamic batch map from any models associated with it.

func (*Model) DynamicBatchRemove added in v0.9.0

func (model *Model) DynamicBatchRemove(batched ...*Model)

DynamicBatchRemove removes the specified batched Models from the calling Model's dynamic batch slice.

func (*Model) DynamicBatchTriangleCount added in v0.9.0

func (model *Model) DynamicBatchTriangleCount() int

DynamicBatchTriangleCount returns the total number of triangles of Models in the calling Model's dynamic batch.

func (*Model) DynamicBatcher added in v0.15.0

func (model *Model) DynamicBatcher() bool

func (*Model) Index added in v0.11.2

func (model *Model) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*Model) ProcessVertices added in v0.9.0

func (model *Model) ProcessVertices(vpMatrix Matrix4, camera *Camera, meshPart *MeshPart, processOnlyVisible bool) []sortingTriangle

ProcessVertices processes the vertices a Model has in preparation for rendering, given a view-projection matrix, a camera, and the MeshPart being rendered.

func (*Model) ReassignBones

func (model *Model) ReassignBones(armatureRoot INode)

ReassignBones reassigns the model to point to a different armature. armatureNode should be a pointer to the starting object Node of the armature (not any of its bones).

func (*Model) Sector added in v0.12.1

func (model *Model) Sector() *Sector

func (*Model) StaticMerge added in v0.11.0

func (model *Model) StaticMerge(models ...*Model)

StaticMerge statically merges the provided models into the calling Model's mesh, such that their vertex properties (position, normal, UV, etc) are part of the calling Model's Mesh. You can use this to merge several objects initially dynamically placed into the calling Model's mesh, thereby pulling back to a single draw call. Note that models are merged into MeshParts (saving draw calls) based on maximum vertex count and shared materials (so to get any benefit from merging, ensure the merged models share materials; if they all have unique materials, they will be turned into individual MeshParts, thereby forcing multiple draw calls). Also note that as the name suggests, this is static merging, which means that after merging, the new vertices are static - part of the merging Model. For more information, see this Wiki page on batching / merging: https://github.com/SolarLune/Tetra3d/wiki/Merging-and-Batching-Draw-Calls

func (*Model) Type added in v0.8.1

func (model *Model) Type() NodeType

Type returns the NodeType for this object.

func (*Model) Unparent

func (model *Model) Unparent()

Unparent unparents the Model from its parent, removing it from the scenegraph.

type Node

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

func NewNode

func NewNode(name string) *Node

NewNode returns a new Node.

func (*Node) AddChildren

func (node *Node) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*Node) AnimationPlayer

func (node *Node) AnimationPlayer() *AnimationPlayer

AnimationPlayer returns the object's animation player - every object has an AnimationPlayer by default.

func (*Node) Children

func (node *Node) Children() []INode

Children returns the Node's children as a slice of INodes.

func (*Node) ClearLocalTransform added in v0.13.0

func (node *Node) ClearLocalTransform()

ClearLocalTransform clears the local transform properties (position, scale, and rotation) for the Node, reverting it to essentially an identity matrix (0, 0, 0 for position, 1, 1, 1 for scale, and an identity Matrix4 for rotation, indicating no rotation). This can be useful because by default, when you parent one Node to another, the local transform properties (position, scale, and rotation) are altered to keep the object in the same absolute location, even though the origin changes.

func (*Node) Clone

func (node *Node) Clone() INode

Clone returns a new Node.

func (*Node) Data

func (node *Node) Data() interface{}

Data returns a pointer to user-customizeable data that could be usefully stored on this node.

func (*Node) DistanceSquaredTo added in v0.14.0

func (node *Node) DistanceSquaredTo(other INode) float64

DistanceSquaredTo returns the squared distance between the given Nodes' centers. Quick syntactic sugar for Node.WorldPosition().DistanceSquared(otherNode.WorldPosition()).

func (*Node) DistanceTo added in v0.13.0

func (node *Node) DistanceTo(other INode) float64

DistanceTo returns the distance between the given Nodes' centers. Quick syntactic sugar for Node.WorldPosition().Distance(otherNode.WorldPosition()).

func (*Node) FindNode added in v0.14.0

func (node *Node) FindNode(nodeName string) INode

FindNode searches through a Node's tree for the node by name. This is mostly syntactic sugar for Node.SearchTree().ByName(nodeName).First().

func (*Node) Get

func (node *Node) Get(path string) INode

Get searches a node's hierarchy using a string to find a specified node. The path is in the format of names of nodes, separated by forward slashes ('/'), and is relative to the node you use to call Get. As an example of Get, if you had a cup parented to a desk, which was parented to a room, that was finally parented to the root of the scene, it would be found at "Room/Desk/Cup". Note also that you can use "../" to "go up one" in the hierarchy (so cup.Get("../") would return the Desk node). Since Get uses forward slashes as path separation, it would be good to avoid using forward slashes in your Node names. Also note that Get() trims the extra spaces from the beginning and end of Node Names, so avoid using spaces at the beginning or end of your Nodes' names.

func (*Node) Grow added in v0.5.0

func (node *Node) Grow(x, y, z float64)

Grow scales the object additively using the x, y, and z arguments provided (i.e. calling Node.Grow(1, 0, 0) will scale it +1 on the X-axis).

func (*Node) GrowVec added in v0.10.0

func (node *Node) GrowVec(vec Vector)

GrowVec scales the object additively using the scaling vector provided (i.e. calling Node.GrowVec(Vector{1, 0, 0}) will scale it +1 on the X-axis).

func (*Node) HierarchyAsString added in v0.8.1

func (node *Node) HierarchyAsString() string

func (*Node) ID added in v0.11.2

func (node *Node) ID() uint64

ID returns the object's unique ID.

func (*Node) Index added in v0.11.2

func (node *Node) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*Node) IsBone added in v0.4.3

func (node *Node) IsBone() bool

IsBone returns if the Node is a "bone" (a node that was a part of an armature and so can play animations back to influence a skinned mesh).

func (*Node) Library added in v0.8.1

func (node *Node) Library() *Library

Library returns the Library from which this Node was instantiated. If it was created through code, this will be nil.

func (*Node) LocalPosition

func (node *Node) LocalPosition() Vector

LocalPosition returns a 3D Vector consisting of the object's local position (position relative to its parent). If this object has no parent, the position will be relative to world origin (0, 0, 0).

func (*Node) LocalRotation

func (node *Node) LocalRotation() Matrix4

LocalRotation returns the object's local rotation Matrix4.

func (*Node) LocalScale

func (node *Node) LocalScale() Vector

LocalScale returns the object's local scale (scale relative to its parent). If this object has no parent, the scale will be absolute.

func (*Node) Move

func (node *Node) Move(x, y, z float64)

Move moves a Node in local space by the x, y, and z values provided.

func (*Node) MoveVec added in v0.5.0

func (node *Node) MoveVec(vec Vector)

MoveVec moves a Node in local space using the vector provided.

func (*Node) Name

func (node *Node) Name() string

Name returns the object's name.

func (*Node) Parent

func (node *Node) Parent() INode

Parent returns the Node's parent. If the Node has no parent, this will return nil.

func (*Node) Path

func (node *Node) Path() string

Path returns a string indicating the hierarchical path to get this Node from the root. The path returned will be absolute, such that passing it to Get() called on the scene root node will return this node. The path returned will not contain the root node's name ("Root"). If the Node is not in a scene tree (i.e. does not have a path to a root node), Path() will return a blank string.

func (*Node) Properties added in v0.11.0

func (node *Node) Properties() Properties

Properties represents an unordered set of game properties that can be used to identify this object.

func (*Node) ReindexChild added in v0.11.2

func (node *Node) ReindexChild(child INode, newPosition int) int

ReindexChild moves the child in the calling Node's children slice to the specified newPosition. The function returns the old index where the child Node was, or -1 if it wasn't a child of the calling Node. The newPosition is clamped to the size of the node's children slice.

func (*Node) RemoveChildren

func (node *Node) RemoveChildren(children ...INode)

RemoveChildren removes the provided children from this object.

func (*Node) ResetWorldPosition added in v0.14.0

func (node *Node) ResetWorldPosition()

ResetWorldPosition resets the Node's local position to the value the Node had when it was first instantiated in the Scene or cloned.

func (*Node) ResetWorldRotation added in v0.14.0

func (node *Node) ResetWorldRotation()

ResetWorldRotation resets the Node's local rotation to the value the Node had when it was first instantiated in the Scene or cloned.

func (*Node) ResetWorldScale added in v0.14.0

func (node *Node) ResetWorldScale()

ResetWorldScale resets the Node's local scale to the value the Node had when it was first instantiated in the Scene or cloned.

func (*Node) ResetWorldTransform added in v0.14.0

func (node *Node) ResetWorldTransform()

ResetWorldTransform resets the Node's world transform properties (position, scale, and rotation) for the Node to the original values when the Node was first instantiated in the Scene or cloned.

func (*Node) Root

func (node *Node) Root() INode

Root returns the root node in the scene by recursively traversing this node's hierarchy of parents upwards. If, instead, the node this is called on is the root (and so has no parents), this function returns the node itself. If the node is not the root and it has no path to the scene root, this function returns nil.

func (*Node) Rotate

func (node *Node) Rotate(x, y, z, angle float64)

Rotate rotates a Node on its local orientation on a vector composed of the given x, y, and z values, by the angle provided in radians.

func (*Node) RotateVec added in v0.10.0

func (node *Node) RotateVec(vec Vector, angle float64)

RotateVec rotates a Node on its local orientation on the given vector, by the angle provided in radians.

func (*Node) Scene added in v0.8.1

func (node *Node) Scene() *Scene

Scene looks for the Node's parents recursively to return what scene it exists in. If the node is not within a tree (i.e. unparented), this will return nil.

func (*Node) SearchTree added in v0.12.0

func (node *Node) SearchTree() *NodeFilter

SearchTree returns a NodeFilter to search through and filter a Node's hierarchy.

func (*Node) Sector added in v0.13.0

func (node *Node) Sector() *Sector

Sector returns the Sector this node is in hierarchically. If that fails, then Sector() will search the scene tree spatially to see which of the sectors the calling Node lies in.

func (*Node) SectorType added in v0.15.0

func (node *Node) SectorType() SectorType

SectorType returns the current SectorType of the Node.

func (*Node) SetData

func (node *Node) SetData(data interface{})

SetData sets user-customizeable data that could be usefully stored on this node.

func (*Node) SetLocalPosition

func (node *Node) SetLocalPosition(x, y, z float64)

SetLocalPosition sets the object's local position (position relative to its parent). If this object has no parent, the position should be relative to world origin (0, 0, 0). position should be a 3D vector (i.e. X, Y, and Z components).

func (*Node) SetLocalPositionVec added in v0.10.0

func (node *Node) SetLocalPositionVec(position Vector)

SetLocalPositionVec sets the object's local position (position relative to its parent). If this object has no parent, the position should be relative to world origin (0, 0, 0). position should be a 3D vector (i.e. X, Y, and Z components).

func (*Node) SetLocalRotation

func (node *Node) SetLocalRotation(rotation Matrix4)

SetLocalRotation sets the object's local rotation Matrix4 (relative to any parent).

func (*Node) SetLocalScale

func (node *Node) SetLocalScale(w, h, d float64)

SetLocalScale sets the object's local scale (scale relative to its parent). If this object has no parent, the scale would be absolute.

func (*Node) SetLocalScaleVec added in v0.10.0

func (node *Node) SetLocalScaleVec(scale Vector)

SetLocalScaleVec sets the object's local scale (scale relative to its parent). If this object has no parent, the scale would be absolute. scale should be a 3D vector (i.e. X, Y, and Z components).

func (*Node) SetName

func (node *Node) SetName(name string)

SetName sets the object's name.

func (*Node) SetSectorType added in v0.15.0

func (node *Node) SetSectorType(sectorType SectorType)

SetSectorType sets the current SectorType of the Node. Note that setting this to Sector won't work.

func (*Node) SetVisible

func (node *Node) SetVisible(visible bool, recursive bool)

SetVisible sets the object's visibility. If recursive is true, all recursive children of this Node will have their visibility set the same way.

func (*Node) SetWorldPosition

func (node *Node) SetWorldPosition(x, y, z float64)

SetWorldPosition sets the object's world position (position relative to the world origin point of {0, 0, 0}).

func (*Node) SetWorldPositionVec added in v0.10.0

func (node *Node) SetWorldPositionVec(position Vector)

SetWorldPositionVec sets the object's world position (position relative to the world origin point of {0, 0, 0}). position needs to be a 3D vector (i.e. X, Y, and Z components).

func (*Node) SetWorldRotation

func (node *Node) SetWorldRotation(rotation Matrix4)

SetWorldRotation sets an object's rotation to the provided rotation Matrix4.

func (*Node) SetWorldScale

func (node *Node) SetWorldScale(w, h, d float64)

SetWorldScale sets the object's absolute world scale.

func (*Node) SetWorldScaleVec added in v0.10.0

func (node *Node) SetWorldScaleVec(scale Vector)

SetWorldScaleVec sets the object's absolute world scale. scale should be a 3D vector (i.e. X, Y, and Z components).

func (*Node) SetWorldTransform added in v0.8.1

func (node *Node) SetWorldTransform(transform Matrix4)

SetWorldTransform sets the Node's global (world) transform to the full 4x4 transformation matrix provided.

func (*Node) SetWorldX added in v0.11.0

func (node *Node) SetWorldX(x float64)

SetWorldX sets the X component of the object's world position.

func (*Node) SetWorldY added in v0.11.0

func (node *Node) SetWorldY(y float64)

SetWorldY sets the Y component of the object's world position.

func (*Node) SetWorldZ added in v0.11.0

func (node *Node) SetWorldZ(z float64)

SetWorldZ sets the Z component of the object's world position.

func (*Node) String added in v0.12.0

func (node *Node) String() string

func (*Node) Transform

func (node *Node) Transform() Matrix4

Transform returns a Matrix4 indicating the global position, rotation, and scale of the object, transforming it by any parents'. If there's no change between the previous Transform() call and this one, Transform() will return a cached version of the transform for efficiency.

func (*Node) Type added in v0.8.1

func (node *Node) Type() NodeType

Type returns the NodeType for this object.

func (*Node) Unparent

func (node *Node) Unparent()

Unparent unparents the Node from its parent, removing it from the scenegraph. Note that this needs to be overridden for objects that embed Node.

func (*Node) Visible

func (node *Node) Visible() bool

Visible returns whether the Object is visible.

func (*Node) WorldPosition

func (node *Node) WorldPosition() Vector

WorldPosition returns a 3D Vector consisting of the object's world position (position relative to the world origin point of {0, 0, 0}).

func (*Node) WorldRotation

func (node *Node) WorldRotation() Matrix4

WorldRotation returns an absolute rotation Matrix4 representing the object's rotation. Note that this is a bit slow as it requires decomposing the node's world transform, so you want to use node.LocalRotation() if you can and performacne is a concern.

func (*Node) WorldScale

func (node *Node) WorldScale() Vector

WorldScale returns the object's absolute world scale as a 3D vector (i.e. X, Y, and Z components). Note that this is a bit slow as it requires decomposing the node's world transform, so you want to use node.LocalScale() if you can and performacne is a concern.

type NodeFilter added in v0.8.1

type NodeFilter struct {
	Filters        []func(INode) bool // The slice of filters that are currently active on the NodeFilter.
	Start          INode              // The start (root) of the filter.
	StopOnFiltered bool               // If the filter should continue through to a node's children if the node itself doesn't pass the filter
	MaxDepth       int                // How deep the node filter should search in the starting node's hierarchy; a value that is less than zero means the entire tree will be traversed.
	// contains filtered or unexported fields
}

NodeFilter represents a chain of node filters, executed in sequence to collect the desired nodes out of an entire hierarchy. The filters are executed lazily (so only one slice is allocated in the process, and possibly one more for the end result, if you get the result as not just a slice of INodes).

func (NodeFilter) ByFunc added in v0.8.1

func (nf NodeFilter) ByFunc(filterFunc func(node INode) bool) NodeFilter

ByFunc allows you to filter a given selection of nodes by the provided filter function (which takes a Node and returns a boolean, indicating whether or not to add that Node to the resulting NodeFilter). If no matching Nodes are found, an empty NodeFilter is returned.

func (NodeFilter) ByName added in v0.8.1

func (nf NodeFilter) ByName(name string) NodeFilter

ByName allows you to filter a given selection of nodes if their names are wholly equal to the provided name string. If a Node's name doesn't match, it isn't added to the filter results.

func (NodeFilter) ByParentProps added in v0.13.0

func (nf NodeFilter) ByParentProps(propNames ...string) NodeFilter

ByParentProps allows you to filter a given selection of nodes if the node has a parent with the provided set of property names. If no matching Nodes are found, an empty NodeFilter is returned.

func (NodeFilter) ByProp added in v0.15.0

func (nf NodeFilter) ByProp(propName string, propValue any) NodeFilter

ByProp allows you to filter a given selection of nodes by a property value check - if the nodes filtered have a property with the given value, they are included. If no matching Nodes are found, an empty NodeFilter is returned.

func (NodeFilter) ByPropNames added in v0.15.0

func (nf NodeFilter) ByPropNames(propNames ...string) NodeFilter

ByPropNames allows you to filter a given selection of nodes by the provided set of property names. If the Nodes in the filter have properties by the given name, they pass the filter and are included. If no matching Nodes are found, an empty NodeFilter is returned.

func (NodeFilter) ByRegex added in v0.11.1

func (nf NodeFilter) ByRegex(regexString string) NodeFilter

ByRegex allows you to filter a given selection of nodes by their namers using the given regex string. If you want to filter a selection of nodes in such a way that only nodes that have names that >contain< the given text (i.e. strings.Contains()) are selected for filtering, you can just pass that string into ByRegex directly. If the regexp string is invalid or no matching Nodes are found, the node isn't added to the filter results. See https://regexr.com/ for regex help / reference.

func (NodeFilter) ByType added in v0.8.1

func (nf NodeFilter) ByType(nodeType NodeType) NodeFilter

ByType allows you to filter a given selection of nodes by the provided NodeType. If no matching Nodes are found, an empty NodeFilter is returned.

func (NodeFilter) Contains added in v0.11.2

func (nf NodeFilter) Contains(node INode) bool

Contains returns if the provided Node is contained in the NodeFilter.

func (NodeFilter) Count added in v0.14.0

func (nf NodeFilter) Count() int

Count returns the number of Nodes that fit the filter set.

func (NodeFilter) Empty added in v0.8.1

func (nf NodeFilter) Empty() bool

Empty returns true if the NodeFilter contains no Nodes.

func (NodeFilter) First added in v0.8.1

func (nf NodeFilter) First() INode

First returns the first Node in the NodeFilter; if the NodeFilter is empty, this function returns nil.

func (NodeFilter) ForEach added in v0.12.0

func (nf NodeFilter) ForEach(f func(node INode) bool)

ForEach executes the provided function on each filtered Node, without allocating memory for a slice of the nodes. The function must return a boolean indicating whether to continue running on each node in the tree that fulfills the filter set (true) or not (false). ForEach does not work with any sorting, and will log a warning if you use sorting and ForEach on the same filter.

func (NodeFilter) Get added in v0.8.1

func (nf NodeFilter) Get(index int) INode

Get returns the Node at the given index in the NodeFilter; if index is invalid (<0 or >= len(nodes)), this function returns nil.

func (NodeFilter) Grids added in v0.10.0

func (nf NodeFilter) Grids() []*Grid

Grids returns a slice of the Grid nodes contained within the NodeFilter.

func (NodeFilter) IBoundingObjects added in v0.13.0

func (nf NodeFilter) IBoundingObjects() []IBoundingObject

IBoundingObjects returns a slice of the IBoundingObjects contained within the NodeFilter.

func (NodeFilter) IBoundingObjectsWithProps added in v0.13.0

func (nf NodeFilter) IBoundingObjectsWithProps(props ...string) []IBoundingObject

IBoundingObjectsWithProps is a helper function that returns a slice of IBoundingObjects who have parents with the specified properties.

func (NodeFilter) INodes added in v0.12.0

func (nf NodeFilter) INodes() []INode

INodes returns the NodeFilter's results as a slice of INodes.

func (NodeFilter) Index added in v0.11.2

func (nf NodeFilter) Index(node INode) int

Index returns the index of the given INode in the NodeFilter; if it doesn't exist in the filter, then this function returns -1.

func (NodeFilter) Last added in v0.8.1

func (nf NodeFilter) Last() INode

First returns the last Node in the NodeFilter; if the NodeFilter is empty, this function returns nil.

func (NodeFilter) Lights added in v0.10.0

func (nf NodeFilter) Lights() []ILight

Lights returns a slice of the ILights contained within the NodeFilter.

func (NodeFilter) Models added in v0.10.0

func (nf NodeFilter) Models() []*Model

Models returns a slice of the Models contained within the NodeFilter.

func (NodeFilter) Not added in v0.13.0

func (nf NodeFilter) Not(others ...INode) NodeFilter

Not allows you to filter OUT a given NodeFilter of nodes. If a node is in the provided slice of INodes, then it will not be added to the final NodeFilter.

func (NodeFilter) SetMaxDepth added in v0.15.0

func (nf NodeFilter) SetMaxDepth(depth int) NodeFilter

SetDepth sets the maximum search depth of the NodeFilter to the value provided.

func (NodeFilter) SortByDistance added in v0.14.0

func (nf NodeFilter) SortByDistance(to Vector) NodeFilter

SortByDistance sorts the results of the NodeFilter by their distances to the specified INode. Sorts do not combine.

func (NodeFilter) SortByX added in v0.14.0

func (nf NodeFilter) SortByX() NodeFilter

SortByX applies an X-axis sort on the results of the NodeFilter. Sorts do not combine.

func (NodeFilter) SortByY added in v0.14.0

func (nf NodeFilter) SortByY() NodeFilter

SortByY applies an Y-axis sort on the results of the NodeFilter. Sorts do not combine.

func (NodeFilter) SortByZ added in v0.14.0

func (nf NodeFilter) SortByZ() NodeFilter

SortByZ applies an Z-axis sort on the results of the NodeFilter. Sorts do not combine.

func (NodeFilter) SortRandom added in v0.14.0

func (nf NodeFilter) SortRandom() NodeFilter

SortReverse randomizes the elements returned by the NodeFilter finishing functions. Sorts do not combine.

func (NodeFilter) SortReverse added in v0.14.0

func (nf NodeFilter) SortReverse() NodeFilter

SortReverse reverses any sorting performed on the NodeFilter.

type NodeType added in v0.8.1

type NodeType string

NodeType represents a Node's type. Node types are categorized, and can be said to extend or "be of" more general types. For example, a BoundingSphere has a type of NodeTypeBoundingSphere. That type can also be said to be NodeTypeBoundingObject (because it is a bounding object). However, it is not of type NodeTypeBoundingTriangles, as that is a different category.

const (
	NodeTypeNode      NodeType = "NodeNode"       // NodeTypeNode represents specifically a node
	NodeTypeModel     NodeType = "NodeModel"      // NodeTypeModel represents specifically a Model
	NodeTypeCamera    NodeType = "NodeCamera"     // NodeTypeCamera represents specifically a Camera
	NodeTypePath      NodeType = "NodePath"       // NodeTypePath represents specifically a Path
	NodeTypeGrid      NodeType = "NodeGrid"       // NodeTypeGrid represents specifically a Grid
	NodeTypeGridPoint NodeType = "Node_GridPoint" // NodeTypeGrid represents specifically a GridPoint (note the extra underscore to ensure !NodeTypeGridPoint.Is(NodeTypeGrid))

	NodeTypeBoundingObject    NodeType = "NodeBounding"          // NodeTypeBoundingObject represents any generic bounding object
	NodeTypeBoundingAABB      NodeType = "NodeBoundingAABB"      // NodeTypeBoundingAABB represents specifically a BoundingAABB
	NodeTypeBoundingCapsule   NodeType = "NodeBoundingCapsule"   // NodeTypeBoundingCapsule represents specifically a BoundingCapsule
	NodeTypeBoundingTriangles NodeType = "NodeBoundingTriangles" // NodeTypeBoundingTriangles represents specifically a BoundingTriangles object
	NodeTypeBoundingSphere    NodeType = "NodeBoundingSphere"    // NodeTypeBoundingSphere represents specifically a BoundingSphere BoundingObject

	NodeTypeLight            NodeType = "NodeLight"            // NodeTypeLight represents any generic light
	NodeTypeAmbientLight     NodeType = "NodeLightAmbient"     // NodeTypeAmbientLight represents specifically an ambient light
	NodeTypePointLight       NodeType = "NodeLightPoint"       // NodeTypePointLight represents specifically a point light
	NodeTypeDirectionalLight NodeType = "NodeLightDirectional" // NodeTypeDirectionalLight represents specifically a directional (sun) light
	NodeTypeCubeLight        NodeType = "NodeLightCube"        // NodeTypeCubeLight represents, specifically, a cube light

)

func (NodeType) Is added in v0.8.1

func (nt NodeType) Is(other NodeType) bool

Is returns true if a NodeType satisfies another NodeType category. A specific node type can be said to contain a more general one, but not vice-versa. For example, a Model (which has type NodeTypeModel) can be said to be a Node (NodeTypeNode), but the reverse is not true (a NodeTypeNode is not a NodeTypeModel).

type Particle added in v0.10.0

type Particle struct {
	ParticleSystem *ParticleSystem
	ModelBank      []*Model // Bank of models the particle could possibly use
	Model          *Model   // The currently active Model

	Velocity Vector // The constant velocity of the Particle in world-space

	VelocityAdd Vector // The acceleration of the Particle in world-space; these values are added to the particle's velocity each frame.
	ScaleAdd    Vector // The growth of the Particle in world-space
	RotationAdd Vector // The additive rotation of the Particle in local-space

	Life     float64                // How long the particle has left to live
	Lifetime float64                // How long the particle lives, maximum
	Data     map[string]interface{} // A custom Data map for storing and retrieving data
}

Particle represents a particle, rendered in a ParticleSystem.

func NewParticle added in v0.10.0

func NewParticle(partSystem *ParticleSystem, partModels []*Model) *Particle

NewParticle creates a new Particle for the given particle system, with the provided slice of particle factories to make particles from.

func (*Particle) Reinit added in v0.10.0

func (part *Particle) Reinit()

func (*Particle) Update added in v0.10.0

func (part *Particle) Update(dt float64)

Update updates the particle's color and movement.

type ParticleSystem added in v0.10.0

type ParticleSystem struct {
	LivingParticles []*Particle

	DeadParticles []*Particle
	On            bool

	ParticleFactories []*Model
	Root              *Model

	Settings *ParticleSystemSettings
	// contains filtered or unexported fields
}

ParticleSystem represents a collection of particles.

func NewParticleSystem added in v0.10.0

func NewParticleSystem(baseModel *Model, particles ...*Model) *ParticleSystem

NewParticleSystem creates a new ParticleSystem, operating on the baseModel Model and randomly creating particles from the provided collection of particle Models.

func (*ParticleSystem) Clone added in v0.10.0

func (ps *ParticleSystem) Clone() *ParticleSystem

Clone creates a duplicate of the given ParticleSystem.

func (*ParticleSystem) Remove added in v0.10.0

func (ps *ParticleSystem) Remove(part *Particle)

Remove removes a particle from the ParticleSystem, recycling the Particle for the next time a particle is spawned.

func (*ParticleSystem) Spawn added in v0.10.0

func (ps *ParticleSystem) Spawn()

Spawn spawns exactly one particle when called.

func (*ParticleSystem) Update added in v0.10.0

func (ps *ParticleSystem) Update(dt float64)

Update should be called once per tick.

type ParticleSystemSettings added in v0.10.0

type ParticleSystemSettings struct {
	SpawnRate   FloatRange  // SpawnRate is how often a particle is spawned in seconds
	SpawnCount  IntRange    // SpawnCount is how many particles are spawned at a time when a particle is spawned
	Lifetime    FloatRange  // Lifetime is how long a particle lives in seconds
	SpawnOffset VectorRange // The range indicating how far of an offset to move

	Velocity    VectorRange // The range indicating how fast a particle constantly moves per frame
	VelocityAdd VectorRange // The range indicating how fast a particle accelerates per frame

	Scale    VectorRange // The range indicating how large the particle should spawn in as
	ScaleAdd VectorRange // The range indicating how large the particle should grow per frame

	RotationAdd        VectorRange // The range indicating how fast a particle should spin per frame
	LocalPosition      bool        // Whether the particles' positions should be local to the system or not; defaults to false.
	Friction           float64     // Friction to apply to velocity
	AllowNegativeScale bool        // If negative scale should be allowed for particles. By default, this is false.

	VertexSpawnMode  int // VertexSpawnMode influences where a particle spawns. By default, this is ParticleVertexSpawnModeOff.
	VertexSpawnModel *Model

	// SpawnOffsetFunction is a function the user can use to customize spawning position of the particles within the system. This function
	// is called additively to the SpawnOffset setting.
	SpawnOffsetFunction func(particle *Particle)

	// MovementFunction is a function the user can use to customize movement of the particles within the system. This function
	// is called additively to the other movement settings.
	MovementFunction func(particle *Particle)

	// Todo: Add curves for all features?
	ColorCurve ColorCurve // ColorCurve is a curve indicating how the spawned particles should change color as they live.
}

func NewParticleSystemSettings added in v0.10.0

func NewParticleSystemSettings() *ParticleSystemSettings

NewParticleSystemSettings creates a new particle system settings.

func (*ParticleSystemSettings) Clone added in v0.10.0

Clone duplicates the ParticleSystemSettings.

type Path added in v0.8.1

type Path struct {
	*Node
	Closed    bool // Closed indicates if a Path is closed (and so going to the end will return to the start) or not.
	PathIndex int  // Index of the path points; used to reset the path when navigating through Path.Next().
}

A Path represents a Node that represents a sequential path. All children of the Path are considered its points, in order.

func NewPath added in v0.8.1

func NewPath(name string, points ...Vector) *Path

NewPath returns a new Path object. A Path is a Node whose children represent points on a path. A Path can be stepped through spatially using a Navigator. The passed point vectors will become Nodes, children of the Path.

func (*Path) AddChildren added in v0.8.1

func (path *Path) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*Path) Clone added in v0.8.1

func (path *Path) Clone() INode

Clone creates a clone of the Path and its points.

func (*Path) HopCount added in v0.15.0

func (path *Path) HopCount() int

HopCount returns the number of hops in the path (i.e. number of nodes - 1).

func (*Path) Index added in v0.11.2

func (path *Path) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*Path) Length added in v0.14.0

func (path *Path) Length() float64

Length returns the total distance that a Path covers by stepping through all of the children under the Path.

func (*Path) Next added in v0.14.0

func (path *Path) Next() (Vector, bool)

Next returns the next point in the path as an iterator - if the boolean value is true, you have reached the end of the path. Useful if you don't want to use a Navigator to navigate through it.

func (*Path) Points added in v0.12.0

func (path *Path) Points() []Vector

Points returns the Vector world positions of each point in the Path.

func (*Path) Type added in v0.8.1

func (path *Path) Type() NodeType

Type returns the NodeType for this object.

func (*Path) Unparent added in v0.8.1

func (path *Path) Unparent()

Unparent unparents the Path from its parent, removing it from the scenegraph.

type PathStepper added in v0.14.0

type PathStepper struct {
	Index int
	// contains filtered or unexported fields
}

PathStepper is an object that steps through points in a set path, returning the position of the current node and the ability to go to the next or previous node in the path.

func NewPathStepper added in v0.14.0

func NewPathStepper(path IPath) *PathStepper

NewPathStepper returns a new PathStepper object.

func (*PathStepper) AtEnd added in v0.14.0

func (ps *PathStepper) AtEnd() bool

AtEnd returns if the PathStepper is at the end of its path.

func (*PathStepper) AtStart added in v0.14.0

func (ps *PathStepper) AtStart() bool

AtStart returns if the PathStepper is at the start of its path.

func (*PathStepper) CurrentWorldPosition added in v0.14.0

func (ps *PathStepper) CurrentWorldPosition() Vector

CurrentWorldPosition returns the current node's world position for the PathStepper.

func (*PathStepper) Next added in v0.14.0

func (ps *PathStepper) Next()

Next steps to the next point in the Path for the PathStepper. If the PathStepper is at the end of the path, then it will loop through the path again.

func (*PathStepper) Path added in v0.14.0

func (ps *PathStepper) Path() IPath

Path returns the path used by the PathStepper.

func (*PathStepper) Prev added in v0.14.0

func (ps *PathStepper) Prev()

Next steps to the previous point in the Path for the PathStepper. If the PathStepper is at the beginning of the path, then it will loop through the path again.

func (*PathStepper) ProgressToWorldPosition added in v0.14.0

func (ps *PathStepper) ProgressToWorldPosition(perc float64) Vector

ProgressToWorldPosition returns a position on the PathStepper's current Path, if given a percentage value that ranges from 0 to 1. The percentage is weighted for distance, not for number of points. For example, say you had a path comprised of four points: {0, 0, 0}, {9, 0, 0}, {9.5, 0, 0}, and {10, 0, 0}. If you called PathStepper.ProgressToWorldPosition(0.9), you'd get {9, 0, 0} (90% of the way through the path). If the PathStepper has a nil Path or its Path has no points, this function returns an empty Vector.

func (*PathStepper) SetIndexToEnd added in v0.14.0

func (ps *PathStepper) SetIndexToEnd()

SetIndexToEnd sets the PathStepper to the point at the end of the path.

func (*PathStepper) SetIndexToStart added in v0.14.0

func (ps *PathStepper) SetIndexToStart()

SetIndexToStart resets the PathStepper to point to the beginning of the path.

func (*PathStepper) SetPath added in v0.14.0

func (ps *PathStepper) SetPath(path IPath)

SetPath sets the path of the PathStepper; this should be called whenever the path updates. Doing this will reset the PathStepper's index to 0.

type PointLight added in v0.5.0

type PointLight struct {
	*Node
	// Range represents the distance after which the light fully attenuates. If this is 0 (the default),
	// it falls off using something akin to the inverse square law.
	Range float64

	// If the light is on and contributing to the scene.
	On bool
	// contains filtered or unexported fields
}

PointLight represents a point light (naturally).

func NewPointLight added in v0.5.0

func NewPointLight(name string, r, g, b, energy float32) *PointLight

NewPointLight creates a new Point light.

func (*PointLight) AddChildren added in v0.5.0

func (p *PointLight) AddChildren(children ...INode)

AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.

func (*PointLight) Clone added in v0.5.0

func (p *PointLight) Clone() INode

Clone returns a new clone of the given point light.

func (*PointLight) Color added in v0.5.0

func (p *PointLight) Color() Color

func (*PointLight) Energy added in v0.5.0

func (p *PointLight) Energy() float32

func (*PointLight) Index added in v0.11.2

func (p *PointLight) Index() int

Index returns the index of the Node in its parent's children list. If the node doesn't have a parent, its index will be -1.

func (*PointLight) IsOn added in v0.10.0

func (p *PointLight) IsOn() bool

func (*PointLight) Light added in v0.5.0

func (p *PointLight) Light(meshPart *MeshPart, model *Model, targetColors []Color, onlyVisible bool)

Light returns the R, G, and B values for the PointLight for all vertices of a given Triangle.

func (*PointLight) SetColor added in v0.15.0

func (p *PointLight) SetColor(color Color)

func (*PointLight) SetEnergy added in v0.15.0

func (p *PointLight) SetEnergy(energy float32)

func (*PointLight) SetOn added in v0.10.0

func (p *PointLight) SetOn(on bool)

func (*PointLight) Type added in v0.8.1

func (p *PointLight) Type() NodeType

Type returns the NodeType for this object.

func (*PointLight) Unparent added in v0.5.0

func (p *PointLight) Unparent()

Unparent unparents the PointLight from its parent, removing it from the scenegraph.

type Properties added in v0.11.0

type Properties map[string]*Property

Properties is an unordered map of property names to values, representing a means of identifying Nodes or carrying data on Nodes.

func NewProperties added in v0.11.0

func NewProperties() Properties

NewProperties returns a new Properties object.

func (Properties) Add added in v0.15.0

func (props Properties) Add(propName string) *Property

Add adds a property to the Properties map using the given name. If a property of the specified name already exists, it will return that property instead.

func (Properties) Clear added in v0.11.0

func (props Properties) Clear()

Clear clears the Properties object of all game properties.

func (Properties) Clone added in v0.11.0

func (props Properties) Clone() Properties

func (Properties) Get added in v0.11.0

func (props Properties) Get(propName string) *Property

Get returns the value associated with the specified property name. If a property with the passed name (propName) doesn't exist, Get will return nil.

func (Properties) Has added in v0.11.0

func (props Properties) Has(propNames ...string) bool

Has returns true if the Properties object has properties by all of the names specified, and false otherwise.

func (Properties) Remove added in v0.11.0

func (props Properties) Remove(tag string)

Remove removes the tag specified from the Properties object.

type Property added in v0.11.0

type Property struct {
	Value interface{}
}

Property represents a game property on a Node or other resource.

func (*Property) AsBool added in v0.11.1

func (prop *Property) AsBool() bool

AsBool returns the value associated with the Property as a bool. Note that this does not sanity check to ensure the Property is a bool first.

func (*Property) AsColor added in v0.11.0

func (prop *Property) AsColor() Color

AsColor returns the value associated with the Property as a Color clone. Note that this does not sanity check to ensure the Property is a Color first.

func (*Property) AsFloat64 added in v0.11.0

func (prop *Property) AsFloat64() float64

AsFloat returns the value associated with the Property as a float64. Note that this does not sanity check to ensure the Property is a float64 first.

func (*Property) AsInt added in v0.11.0

func (prop *Property) AsInt() int

AsInt returns the value associated with the Property as a float. Note that this does not sanity check to ensure the Property is an int first.

func (*Property) AsString added in v0.11.0

func (prop *Property) AsString() string

AsString returns the value associated with the Property as a string. Note that this does not sanity check to ensure the Property is a string first.

func (*Property) AsVector added in v0.11.0

func (prop *Property) AsVector() Vector

AsVector returns the value associated with the Property as a 3D position Vector clone. The axes are corrected to account for the difference between Blender's axis order and Tetra3D's (i.e. Blender's +X, +Y, +Z becomes Tetra3D's +X, +Z, +Y). Note that this does not sanity check to ensure the Property is a vector first.

func (*Property) IsBool added in v0.11.1

func (prop *Property) IsBool() bool

IsBool returns true if the Property is a boolean value.

func (*Property) IsColor added in v0.11.0

func (prop *Property) IsColor() bool

IsColor returns true if the Property is a color.

func (*Property) IsFloat64 added in v0.11.0

func (prop *Property) IsFloat64() bool

IsFloat returns true if the Property is a float64.

func (*Property) IsInt added in v0.11.0

func (prop *Property) IsInt() bool

IsInt returns true if the Property is an int.

func (*Property) IsString added in v0.11.0

func (prop *Property) IsString() bool

IsString returns true if the Property is a string.

func (*Property) IsVector added in v0.11.0

func (prop *Property) IsVector() bool

IsVector returns true if the Property is a vector.

func (*Property) Set added in v0.11.0

func (prop *Property) Set(value interface{})

Set sets the property's value to the given value.

type Quaternion

type Quaternion struct {
	X, Y, Z, W float64
}

Quaternion is a tool to rotate objects, similar to rotation Matrix4s. However, a difference is that they can very easily be lerped without losing data - if you were to lerp two rotation matrices, you can easily end up with a zero matrix, making your rotating object disappear. Instead, you can create the two Quaternions you need (either from Matrix4s or directly), and then lerp them together.

func NewQuaternion

func NewQuaternion(x, y, z, w float64) Quaternion

func NewQuaternionFromAxisAngle added in v0.11.0

func NewQuaternionFromAxisAngle(axis Vector, angle float64) Quaternion

NewQuaternionFromAxisAngle returns a new Quaternion from the given axis and angle combination.

func (Quaternion) Dot

func (quat Quaternion) Dot(other Quaternion) float64

func (Quaternion) Lerp added in v0.5.0

func (quat Quaternion) Lerp(end Quaternion, percent float64) Quaternion

func (Quaternion) Magnitude added in v0.5.0

func (quat Quaternion) Magnitude() float64

func (Quaternion) Mult added in v0.10.0

func (q1 Quaternion) Mult(q2 Quaternion) Quaternion

func (Quaternion) Negated added in v0.5.0

func (quat Quaternion) Negated() Quaternion

func (Quaternion) Normalized added in v0.5.0

func (quat Quaternion) Normalized() Quaternion

func (Quaternion) RotateVec added in v0.11.0

func (quat Quaternion) RotateVec(v Vector) Vector

RotateVec rotates the given vector around using the Quaternion counter-clockwise.

func (Quaternion) ToAxisAngle added in v0.11.2

func (quat Quaternion) ToAxisAngle() (Vector, float64)

ToAxisAngle returns tha axis Vector and angle (in radians) for a quaternion's rotation.

func (Quaternion) ToMatrix4 added in v0.10.0

func (quat Quaternion) ToMatrix4() Matrix4

ToMatrix4 generates a rotation Matrx4 from the given Quaternion.

type RayHit added in v0.12.0

type RayHit struct {
	Object   INode  // Object is a pointer to the object that was struck by the raycast.
	Position Vector // Position is the world position that the object was struct.

	Normal Vector // Normal is the normal of the surface the ray struck.
	// What triangle the raycast hit - note that this is only set to a non-nil value for raycasts against BoundingTriangle objects
	Triangle *Triangle
	// contains filtered or unexported fields
}

RayHit represents the result of a raycast test.

func RayTest added in v0.12.0

func RayTest(from, to Vector, testAgainst ...IBoundingObject) []RayHit

RayTest casts a ray from the "from" world position to the "to" world position, testing against the provided IBoundingObjects. RayTest returns a slice of RayHit objects sorted from closest to furthest. Note that each object can only be struck once by the raycast, with the exception of BoundingTriangles objects (since a single ray may strike multiple triangles).

func (RayHit) Distance added in v0.13.0

func (r RayHit) Distance() float64

Distance returns the distance from the RayHit's originating ray source point to the struck position.

func (RayHit) Slope added in v0.12.0

func (r RayHit) Slope() float64

Slope returns the slope of the RayHit's normal, in radians. This ranges from 0 (straight up) to pi (straight down).

type Scene

type Scene struct {
	Name string // The name of the Scene. Set automatically to the scene name in your 3D modeler if the DAE file exports it.

	// Root indicates the root node for the scene hierarchy. For visual Models to be displayed, they must be added to the
	// scene graph by simply adding them into the tree via parenting anywhere under the Root. For them to be removed from rendering,
	// they simply need to be removed from the tree.
	// See this page for more information on how a scene graph works: https://webglfundamentals.org/webgl/lessons/webgl-scene-graph.html
	Root  INode
	World *World

	View3DCameras []*Camera // Any 3D view cameras that were exported from Blender
	// contains filtered or unexported fields
}

Scene represents a world of sorts, and can contain a variety of Meshes and Nodes, which organize the scene into a graph of parents and children. Models (visual instances of Meshes), Cameras, and "empty" NodeBases all are kinds of Nodes.

func NewScene

func NewScene(name string) *Scene

NewScene creates a new Scene by the name given.

func (*Scene) Clone

func (scene *Scene) Clone() *Scene

Clone clones the Scene, returning a copy. Models and Meshes are shared between them.

func (*Scene) Data added in v0.14.0

func (scene *Scene) Data() interface{}

Data returns the Scene's user-customizeable data.

func (*Scene) FindNode added in v0.15.0

func (scene *Scene) FindNode(nodeName string) INode

FindNode searches through a Node's tree for the node by name exactly. This is mostly syntactic sugar for Node.SearchTree().ByName(nodeName).First().

func (*Scene) Get added in v0.15.0

func (scene *Scene) Get(nodePath string) INode

Get searches a node's hierarchy using a string to find a specified node. The path is in the format of names of nodes, separated by forward slashes ('/'), and is relative to the node you use to call Get. As an example of Get, if you had a cup parented to a desk, which was parented to a room, that was finally parented to the root of the scene, it would be found at "Room/Desk/Cup". Note also that you can use "../" to "go up one" in the hierarchy (so cup.Get("../") would return the Desk node). Since Get uses forward slashes as path separation, it would be good to avoid using forward slashes in your Node names. Also note that Get() trims the extra spaces from the beginning and end of Node Names, so avoid using spaces at the beginning or end of your Nodes' names. Syntactic sugar for Scene.Root.Get().

func (*Scene) HandleAutobatch added in v0.11.0

func (scene *Scene) HandleAutobatch()

func (*Scene) Library added in v0.8.1

func (scene *Scene) Library() *Library

Library returns the Library from which this Scene was loaded. If it was created through code and not associated with a Library, this function will return nil.

func (*Scene) Properties added in v0.11.0

func (scene *Scene) Properties() Properties

func (*Scene) SetData added in v0.14.0

func (scene *Scene) SetData(data interface{})

SetData sets the Scene's user-customizeable data pointer to whatever you specify (i.e. a backing "Level" instance or something, for example).

type Sector added in v0.12.1

type Sector struct {
	Model               *Model              // The owning Model that forms the Sector
	AABB                *BoundingAABB       // The AABB used to search for neighbors if the SectorDetectionType is set to SectorDetectionTypeAABB
	Neighbors           Set[*Sector]        // The Sector's neighbors
	SectorDetectionType SectorDetectionType // How the Sector is detected
	// contains filtered or unexported fields
}

Sector represents an area in a game (a sector), and is used for sector-based rendering. When a camera renders a scene with sector-based rendering enabled, the Camera will render only the objects within the current sector and any neighboring sectors, up to a customizeable depth. A Sector is, spatially, an AABB, which sits next to or within other Sectors (AABBs). Logically, a Sector is determined to be a neighbor of another Sector if they either intersect, or share vertex positions. Which of these is the case depends on the Sectors' SectorDetectionType.

func NewSector added in v0.12.1

func NewSector(model *Model) *Sector

NewSector creates a new Sector for the provided Model.

func (*Sector) Clone added in v0.12.1

func (sector *Sector) Clone() *Sector

Clone clones a Sector.

func (*Sector) NeighborsWithinRange added in v0.12.1

func (sector *Sector) NeighborsWithinRange(searchRange int) Set[*Sector]

NeighborsWithinRange returns the neighboring Sectors within a certain search range. For example, given the following example:

A - B - C - D - E - F

If you were to check NeighborsWithinRange(2) from E, it would return F, D, and C.

func (*Sector) UpdateNeighbors added in v0.12.1

func (sector *Sector) UpdateNeighbors(otherModels ...*Model)

UpdateNeighbors updates the Sector's neighbors to refresh it, in case it moves. The Neighbors set is updated, not replaced, by this process (so clear the Sector's NeighborSet first if you need to do so).

type SectorDetectionType added in v0.15.0

type SectorDetectionType int

type SectorType added in v0.15.0

type SectorType int
const (
	SectorTypeObject SectorType = iota
	SectorTypeSector
	SectorTypeStandalone
)

type Set added in v0.15.0

type Set[E comparable] map[E]struct{}

Set represents a Set of elements.

func (Set[E]) Add added in v0.15.0

func (s Set[E]) Add(element E)

Add adds the given elements to a set.

func (Set[E]) Clear added in v0.15.0

func (s Set[E]) Clear()

Clear clears the set.

func (Set[E]) Clone added in v0.15.0

func (s Set[E]) Clone() Set[E]

func (Set[E]) Combine added in v0.15.0

func (s Set[E]) Combine(otherSet Set[E])

Combine combines the given other elements to the set.

func (Set[E]) Contains added in v0.15.0

func (s Set[E]) Contains(element E) bool

Contains returns if the set contains the given element.

func (Set[E]) ForEach added in v0.15.0

func (s Set[E]) ForEach(f func(element E))

ForEach runs the provided function for each element in the set.

func (Set[E]) Remove added in v0.15.0

func (s Set[E]) Remove(element E)

Remove removes the given element from the set.

type Text added in v0.13.0

type Text struct {
	Texture *ebiten.Image // The texture used to render text
	// contains filtered or unexported fields
}

Text represents a helper object that writes text for display as a texture on a Model's MeshPart. Text objects use a pre-made shader to render.

func NewText added in v0.13.0

func NewText(meshPart *MeshPart, textureWidth int) (*Text, error)

NewText creates a new Text rendering surface for typing out text and assigns the MeshPart provided to use that surface as a texture. If the MeshPart has no Material, then a new one will be created with sane default settings. NewText sets the transparency mode of the material to be transparent, as clip alpha doesn't work properly. textureWidth is how wide (in pixels) the backing texture should be for displaying the text; the height is determined by the aspect ratio of the dimensions of the meshpart given. Text objects update the mesh's material to point to an internal texture, and use a shader as well. If you want to tweak the rendering further, do so on the provided MeshPart after calling NewText(). All changes to the Text require that the Text object updates its texture, which can be costly as this means redrawing the text as necessary; this is handled automatically. Note that for this to work ideally, the mesh cannot be rotated (i.e. the mesh's faces should not be at an angle). The function will return an error if the UV values for the vertices don't cover a large enough range (i.e. if the plane doesn't cover the entire text texture, from 0,0 to 1,1). This isn't necessarily a problem, but can indicate an issue that would make text not render.

func NewTextAutoSize added in v0.13.0

func NewTextAutoSize(meshPart *MeshPart, camera *Camera) (*Text, error)

NewTextAutoSize creates a new Text rendering surface for typing out text, with the backing texture's size calculated from an orthographic Camera's render scale. This is generally useful for UI Text objects. Note that for this to work ideally, the mesh cannot be rotated (i.e. the mesh's faces should not be at an angle). All changes to the Text require that the Text object updates its texture, which can be costly as this means redrawing the text as necessary; this is handled automatically. The function will return an error if the UV values for the vertices don't cover a large enough range (i.e. if the plane doesn't cover the entire text texture, from 0,0 to 1,1). This isn't necessarily a problem, but can indicate an issue that would make text not render.

func (*Text) AdvanceTypewriterIndex added in v0.13.0

func (text *Text) AdvanceTypewriterIndex(advanceBy int) bool

AdvanceTypewriterIndex advances the scroll of the text by the number of characters given. AdvanceTypewriterIndex will return a boolean value indicating if the Text advanced to the end or not.

func (*Text) ClearText added in v0.13.0

func (textObj *Text) ClearText() *Text

ClearText clears the text displaying in the Text Object.

func (*Text) Clone added in v0.13.0

func (text *Text) Clone() *Text

Clone clones the Text object.

func (*Text) Dispose added in v0.13.0

func (text *Text) Dispose()

Dispose disposes of the text object's backing texture; this needs to be called to free VRAM, and should be called whenever the owning Model and Mesh are no longer is going to be used. This also will set the texture of the MeshPart this Text object is tied to, to nil.

func (*Text) FinishTypewriter added in v0.13.0

func (text *Text) FinishTypewriter()

FinishTypewriter finishes the typewriter effect, so that the entire message is visible.

func (*Text) SetStyle added in v0.15.0

func (text *Text) SetStyle(style TextStyle)

func (*Text) SetText added in v0.13.0

func (textObj *Text) SetText(txt string, arguments ...interface{}) *Text

SetText sets the text to be displayed for the Text object. arguments can be variables to be displayed in the text string, formatted using fmt.Sprintf()'s formatting rules. Text objects handle automatically splitting newlines based on length to the owning plane mesh's size. Setting the text to be blank clears the text, though Text.ClearText() also exists, and is just syntactic sugar for this purpose. SetText accounts for the margin set in the Text object's active TextStyle, but if it is applied prior to calling SetText().

func (*Text) SetTypewriterIndex added in v0.13.0

func (text *Text) SetTypewriterIndex(typewriterIndex int)

SetTypewriterIndex sets the typewriter scroll of the text to the value given.

func (*Text) SetTypewriterOn added in v0.15.0

func (text *Text) SetTypewriterOn(on bool)

SetTypewriterOn sets the typewriter effect on the Text object.

func (*Text) Style added in v0.15.0

func (text *Text) Style() TextStyle

func (*Text) Text added in v0.13.0

func (text *Text) Text() string

Text returns the current text that is being displayed for the Text object.

func (*Text) TypewriterFinished added in v0.13.0

func (text *Text) TypewriterFinished() bool

TypewriterFinished returns if the typewriter effect is finished.

func (*Text) TypewriterIndex added in v0.13.0

func (text *Text) TypewriterIndex() int

TypewriterIndex returns the typewriter index of the Text object.

func (*Text) TypewriterOn added in v0.15.0

func (text *Text) TypewriterOn() bool

TypewriterOn returns if the typewriter effect is enabled on the Text object.

func (*Text) UpdateTexture added in v0.13.0

func (textObj *Text) UpdateTexture()

UpdateTexture will update the Text's backing texture, clearing and/or redrawing the texture as necessary. This won't do anything if the texture is nil (has been disposed).

type TextAlignment added in v0.14.0

type TextAlignment int
const (
	TextAlignLeft   TextAlignment = iota // Left aligned text. The text hugs the left side of the texture.
	TextAlignCenter                      // Center aligned text. All text lines are centered horizontally in the texture's width.
	TextAlignRight                       // Right aligned text. The text hugs the right side of the texture.
)

type TextStyle added in v0.13.0

type TextStyle struct {
	Font                 font.Face     // The font face to use for rendering the text. The size is customizeable, but the DPI should be 72.
	Cursor               string        // A cursor string sequence is drawn at the end while typewriter-ing; defaults to a blank string ("").
	LineHeightMultiplier float64       // The multiplier for line height changes.
	AlignmentHorizontal  TextAlignment // How the text should be horizontally aligned in the Text texture.

	BGColor Color // The Background color for the text. Defaults to black (0, 0, 0, 1).
	FGColor Color // The Foreground color for the text. Defaults to white (1, 1, 1, 1).

	ShadowDirection Vector // A vector indicating direction of the shadow's heading. Defaults to down-right ( {1, 1, 0}, normalized ).
	ShadowLength    int    // The length of the shadow in pixels. Defaults to 0 (no shadow).
	ShadowColorNear Color  // The color of the shadow near the letters. Defaults to black (0, 0, 0, 1).
	ShadowColorFar  Color  // The color of the shadow towards the end of the letters. Defaults to black (0, 0, 0, 1).

	OutlineThickness int   // Overall thickness of the outline in pixels. Defaults to 0 (no outline).
	OutlineRounded   bool  // If the outline is rounded or not. Defaults to false (square outlines).
	OutlineColor     Color // Color of the outline. Defaults to black (0, 0, 0, 1).

	// Margin (in pixels) of space to leave around the frame of the texture (left or right, depending on HorizontalAlignment, and from the top). Defaults to 0.
	MarginHorizontal, MarginVertical int
}

func NewDefaultTextStyle added in v0.13.0

func NewDefaultTextStyle() TextStyle

type TextureAnimation added in v0.8.1

type TextureAnimation struct {
	FPS    float64  // The playback frame per second (or FPS) of the animation
	Frames []Vector // A slice of vectors, with each indicating the offset of the frame from the original position for the mesh.
}

TextureAnimation is an animation struct. The TextureAnimation.Frames value is a []Vector, with each Vector representing a frame of the animation (and the offset from the original, base position for all animated vertices).

func NewTextureAnimationPixels added in v0.9.0

func NewTextureAnimationPixels(fps float64, image *ebiten.Image, framePositions ...float64) *TextureAnimation

NewTextureAnimationPixels creates a new TextureAnimation using pixel positions instead of UV values. fps is the frames per second for the animation. image is the source texture used, and framePositions are the positions in pixels for each frame (i.e. 32, 32 instead of 0.25, 0.25 on a 128x128 spritesheet). NewTextureAnimationInPixels will panic if given less than 2 values for framePositions, or if it's an odd number of values (i.e. an X value for a frame, but no matching Y Value).

type TexturePlayer added in v0.8.1

type TexturePlayer struct {
	OriginalOffsets map[int]Vector    // OriginalOffsets is a map of vertex indices to their base UV offsets. All animating happens relative to these values.
	Animation       *TextureAnimation // Animation is a pointer to the currently playing Animation.
	// Playhead increases as the TexturePlayer plays. The integer portion of Playhead is the frame that the TexturePlayer
	// resides in (so a Playhead of 1.2 indicates that it is in frame 1, the second frame).
	Playhead float64
	Speed    float64 // Speed indicates the playback speed and direction of the TexturePlayer, with a value of 1.0 being 100%.
	Playing  bool    // Playing indicates whether the TexturePlayer is currently playing or not.
	// contains filtered or unexported fields
}

TexturePlayer is a struct that allows you to animate a collection of vertices' UV values using a TextureAnimation.

func NewTexturePlayer added in v0.8.1

func NewTexturePlayer(vertexSelection *VertexSelection) *TexturePlayer

NewTexturePlayer returns a new TexturePlayer instance.

func (*TexturePlayer) ApplyUVOffset added in v0.8.1

func (player *TexturePlayer) ApplyUVOffset(offsetX, offsetY float64)

ApplyUVOffset applies a specified UV offset to all vertices a player is assigned to. This offset is not additive, but rather is set once, regardless of how many times ApplyUVOffset is called.

func (*TexturePlayer) Play added in v0.8.1

func (player *TexturePlayer) Play(animation *TextureAnimation)

Play plays the passed TextureAnimation, resetting the playhead if the TexturePlayer is not playing an animation. If the player is not playing, it will begin playing.

func (*TexturePlayer) Reset added in v0.8.1

func (player *TexturePlayer) Reset(vertexSelection *VertexSelection)

Reset resets a TexturePlayer to be ready to run on a new selection of vertices. Note that this also resets the base UV offsets to use the current values of the passed vertices in the slice.

func (*TexturePlayer) Update added in v0.8.1

func (player *TexturePlayer) Update(dt float64)

Update updates the TexturePlayer, using the passed delta time variable to animate the TexturePlayer's vertices.

type TreeWatcher added in v0.15.0

type TreeWatcher struct {

	// WatchFilter is a function that is used to filter down which nodes to watch, and is called for each object in the scene tree.
	// If the function returns true, the Node is watched.
	WatchFilter func(node INode) bool
	OnChange    func(node INode) // OnChange is a function that is run for every altered node under a tree's root node whenever anything in that hierarchy is added or removed from the tree.
	// contains filtered or unexported fields
}

TreeWatcher is a utility struct used to watch a tree for hierarchy changes underneath a specific node. This is useful when, for example, adding game logic code for objects added into a scene.

func NewTreeWatcher added in v0.15.0

func NewTreeWatcher(rootNode INode, onChange func(node INode)) *TreeWatcher

NewTreeWatcher creates a new TreeWatcher, a utility that watches the scene tree underneath the rootNode for changes. onChange should be the function that is run for each node when it is added to, or removed from, the tree underneath the rootNode.

func (*TreeWatcher) SetRoot added in v0.15.0

func (watch *TreeWatcher) SetRoot(rootNode INode)

SetRoot sets the root Node to be watched for the TreeWatcher.

func (*TreeWatcher) Update added in v0.15.0

func (watch *TreeWatcher) Update()

Update updates the TreeWatcher instance, and should be run once every game frame.

type Triangle

type Triangle struct {
	ID            uint16
	VertexIndices []int     // Vertex indices that compose the triangle
	MaxSpan       float64   // The maximum span from corner to corner of the triangle's dimensions; this is used in intersection testing.
	Center        Vector    // The untransformed center of the Triangle.
	Normal        Vector    // The physical normal of the triangle (i.e. the direction the triangle is facing). This is different from the visual normals of a triangle's vertices (i.e. a selection of vertices can have inverted normals to be see through, for example).
	MeshPart      *MeshPart // The specific MeshPart this Triangle belongs to.
}

A Triangle represents the smallest renderable object in Tetra3D. A triangle contains very little data, and is mainly used to help identify triads of vertices.

func NewTriangle

func NewTriangle(meshPart *MeshPart, id uint16, indices ...int) *Triangle

NewTriangle creates a new Triangle, and requires a reference to its owning MeshPart, along with its id within that MeshPart.

func (*Triangle) Clone

func (tri *Triangle) Clone() *Triangle

Clone clones the Triangle, keeping a reference to the same Material.

func (*Triangle) ForEachVertexIndex added in v0.11.0

func (tri *Triangle) ForEachVertexIndex(vertFunc func(vertexIndex int))

func (*Triangle) RecalculateCenter

func (tri *Triangle) RecalculateCenter()

RecalculateCenter recalculates the center for the Triangle. Note that this should only be called if you manually change a vertex's individual position.

func (*Triangle) RecalculateNormal

func (tri *Triangle) RecalculateNormal()

RecalculateNormal recalculates the physical normal for the Triangle. Note that this should only be called if you manually change a vertex's individual position. Also note that vertex normals (visual normals) are automatically set when loading Meshes from model files.

func (*Triangle) SharesVertexPositions added in v0.10.0

func (tri *Triangle) SharesVertexPositions(other *Triangle) (int, int, int)

SharesVertexPosition returns 3 ints representing which indices the triangles have in common for the first, second, and third vertices of the calling tri. If no vertices are shared, the indices are all -1.

type Vector added in v0.11.0

type Vector struct {
	X float64 // The X (1st) component of the Vector
	Y float64 // The Y (2nd) component of the Vector
	Z float64 // The Z (3rd) component of the Vector
	W float64 // The w (4th) component of the Vector; not used for most Vector functions
}

Vector represents a 3D Vector, which can be used for usual 3D applications (position, direction, velocity, etc). The fourth component, W, can be ignored and is used for internal Tetra3D usage. Any Vector functions that modify the calling Vector return copies of the modified Vector, meaning you can do method-chaining easily. Vectors seem to be most efficient when copied (so try not to store pointers to them if possible, as dereferencing pointers can be more inefficient than directly acting on data, and storing pointers moves variables to heap).

func NewVector added in v0.11.0

func NewVector(x, y, z float64) Vector

NewVector creates a new Vector with the specified x, y, and z components. The W component is generally ignored for most purposes.

func NewVector2d added in v0.11.0

func NewVector2d(x, y float64) Vector

NewVector creates a new Vector with the specified x and y components. The Z and W components are set to 0.

func NewVectorZero added in v0.11.0

func NewVectorZero() Vector

NewVectorZero creates a new "zero-ed out" Vector, with the values of 0, 0, 0, and 0 (for W).

func (Vector) Add added in v0.11.0

func (vec Vector) Add(other Vector) Vector

Plus returns a copy of the calling vector, added together with the other Vector provided (ignoring the W component).

func (Vector) Angle added in v0.11.0

func (vec Vector) Angle(other Vector) float64

Angle returns the angle in radians between the calling Vector and the provided other Vector (ignoring the W component).

func (Vector) Ceil added in v0.15.0

func (vec Vector) Ceil() Vector

Ceil ceils the Vector's components off, returning a new Vector. For example, Vector{0.1, 1.27, 3.33}.Ceil() will return Vector{1, 2, 4}.

func (Vector) Clamp added in v0.15.0

func (vec Vector) Clamp(x, y, z float64) Vector

Clamp clamps the Vector to the maximum values provided.

func (Vector) ClampAngle added in v0.15.0

func (vec Vector) ClampAngle(baselineVec Vector, maxAngle float64) Vector

ClampAngle clamps the Vector such that it doesn't exceed the angle specified (in radians). This function returns a normalized (unit) Vector.

func (Vector) ClampMagnitude added in v0.11.0

func (vec Vector) ClampMagnitude(maxMag float64) Vector

ClampMagnitude clamps the overall magnitude of the Vector to the maximum magnitude specified, returning a copy with the result. If the magnitude is less than that maximum magnitude, the vector is unmodified.

func (Vector) ClampVec added in v0.15.0

func (vec Vector) ClampVec(extents Vector) Vector

ClampVec clamps the Vector to the maximum values in the Vector provided.

func (Vector) Cross added in v0.11.0

func (vec Vector) Cross(other Vector) Vector

Cross returns a new Vector, indicating the cross product of the calling Vector and the provided Other Vector. This function ignores the W component of both Vectors.

func (Vector) Distance added in v0.11.0

func (vec Vector) Distance(other Vector) float64

Distance returns the distance from the calling Vector to the other Vector provided.

func (Vector) DistanceSquared added in v0.11.0

func (vec Vector) DistanceSquared(other Vector) float64

Distance returns the squared distance from the calling Vector to the other Vector provided. This is faster than Distance(), as it avoids using math.Sqrt().

func (Vector) Divide added in v0.11.0

func (vec Vector) Divide(scalar float64) Vector

Divide divides a Vector by the given scalar (ignoring the W component), returning a copy with the result.

func (Vector) Dot added in v0.11.0

func (vec Vector) Dot(other Vector) float64

Dot returns the dot product of a Vector and another Vector (ignoring the W component).

func (Vector) Equals added in v0.11.0

func (vec Vector) Equals(other Vector) bool

Equals returns true if the two Vectors are close enough in all values (excluding W).

func (Vector) Expand added in v0.11.0

func (vec Vector) Expand(margin, min float64) Vector

Expand expands the Vector by the margin specified, in absolute units, if each component is over the minimum argument. To illustrate: Given a Vector of {1, 0.1, -0.3}, Vector.Expand(0.5, 0.2) would give you a Vector of {1.5, 0.1, -0.8}. This function returns a copy of the Vector with the result.

func (Vector) Floats added in v0.11.0

func (vec Vector) Floats() [4]float64

Floats returns a [4]float64 array consisting of the Vector's contents.

func (Vector) Floor added in v0.15.0

func (vec Vector) Floor() Vector

Floor floors the Vector's components off, returning a new Vector. For example, Vector{0.1, 1.27, 3.33}.Floor() will return Vector{0, 1, 3}.

func (Vector) Invert added in v0.11.0

func (vec Vector) Invert() Vector

Invert returns a copy of the Vector with all components inverted (ignoring the Vector's W component).

func (Vector) IsZero added in v0.11.0

func (vec Vector) IsZero() bool

IsZero returns true if the values in the Vector are extremely close to 0 (excluding W).

func (Vector) Lerp added in v0.15.0

func (vec Vector) Lerp(other Vector, percentage float64) Vector

Lerp performs a linear interpolation between the starting Vector and the provided other Vector, to the given percentage (ranging from 0 to 1).

func (Vector) Magnitude added in v0.11.0

func (vec Vector) Magnitude() float64

Magnitude returns the length of the Vector (ignoring the Vector's W component).

func (Vector) MagnitudeSquared added in v0.11.0

func (vec Vector) MagnitudeSquared() float64

MagnitudeSquared returns the squared length of the Vector (ignoring the Vector's W component); this is faster than Length() as it avoids using math.Sqrt().

func (*Vector) Modify added in v0.11.0

func (vec *Vector) Modify() ModVector

Modify returns a ModVector object (a pointer to the original vector).

func (Vector) Mult added in v0.13.0

func (vec Vector) Mult(other Vector) Vector

Mult performs Hadamard (component-wise) multiplication on the calling Vector with the other Vector provided, returning a copy with the result (and ignoring the Vector's W component).

func (Vector) Rotate added in v0.11.0

func (vec Vector) Rotate(x, y, z, angle float64) Vector

Rotate returns a copy of the Vector, rotated around an axis Vector with the x, y, and z components provided, by the angle provided (in radians), counter-clockwise. The function is most efficient if passed an orthogonal, normalized axis (i.e. the X, Y, or Z constants). Note that this function ignores the W component of both Vectors.

func (Vector) RotateVec added in v0.11.0

func (vec Vector) RotateVec(axis Vector, angle float64) Vector

Rotate returns a copy of the Vector, rotated around the Vector axis provided by the angle provided (in radians). The function is most efficient if passed an orthogonal, normalized axis (i.e. the X, Y, or Z constants). Note that this function ignores the W component of both Vectors.

func (Vector) Round added in v0.15.0

func (vec Vector) Round(roundToUnits float64) Vector

Round rounds the Vector's components off to the given space in world units, returning a new Vector. For example, Vector{0.1, 1.27, 3.33}.Round(0.25) will return Vector{0, 1.25, 3.25}.

func (Vector) Scale added in v0.11.0

func (vec Vector) Scale(scalar float64) Vector

Scale scales a Vector by the given scalar (ignoring the W component), returning a copy with the result.

func (Vector) Set added in v0.11.0

func (vec Vector) Set(x, y, z float64) Vector

Set sets the values in the Vector to the x, y, and z values provided.

func (Vector) SetX added in v0.11.0

func (vec Vector) SetX(x float64) Vector

SetX sets the X component in the vector to the value provided.

func (Vector) SetY added in v0.11.0

func (vec Vector) SetY(y float64) Vector

SetY sets the Y component in the vector to the value provided.

func (Vector) SetZ added in v0.11.0

func (vec Vector) SetZ(z float64) Vector

SetZ sets the Z component in the vector to the value provided.

func (Vector) Slerp added in v0.15.0

func (vec Vector) Slerp(end Vector, percentage float64) Vector

Slerp performs a spherical linear interpolation between the starting Vector and the provided ending Vector, to the given percentage (ranging from 0 to 1). This normalizes both Vectors.

func (Vector) String added in v0.11.0

func (vec Vector) String() string

String returns a string representation of the Vector, excluding its W component (which is primarily used for internal purposes).

func (Vector) StringW added in v0.11.1

func (vec Vector) StringW() string

String returns a string representation of the Vector, excluding its W component (which is primarily used for internal purposes).

func (Vector) Sub added in v0.11.0

func (vec Vector) Sub(other Vector) Vector

Sub returns a copy of the calling Vector, with the other Vector subtracted from it (ignoring the W component).

func (Vector) SubMagnitude added in v0.12.1

func (vec Vector) SubMagnitude(mag float64) Vector

SubMagnitude returns a copy of the Vector with the given magnitude subtracted from it. If the vector's magnitude is less than the given magnitude to subtract, a zero-length Vector will be returned.

func (Vector) Swizzle added in v0.11.0

func (vec Vector) Swizzle(swizzleString string) Vector

Swizzle swizzles the Vector using the string provided, returning the swizzled copy. The string can be of length 3 ("xyz") or 4 ("xyzw"). The string should be composed of the axes of a vector, i.e. 'x', 'y', 'z', or 'w'. Example: `vec := Vector{1, 2, 3}.Swizzle("zxy") // Returns a Vector of {3, 1, 2}.`

func (Vector) Unit added in v0.11.0

func (vec Vector) Unit() Vector

Unit returns a copy of the Vector, normalized (set to be of unit length). It does not alter the W component of the Vector.

type VectorRange added in v0.10.0

type VectorRange struct {
	Uniform bool   // If the random value returned by the NumberRange should be consistent across all axes or not
	Min     Vector // Min is the set of minimum numbers allowed in the NumberRange
	Max     Vector // Max is the set of maximum numbers allowed in the NumberRange
}

VectorRange represents a range of possible values, and allows Tetra3D to get a random value from within that number range.

func NewVectorRange added in v0.10.0

func NewVectorRange() VectorRange

NewVectorRange returns a new instance of a 3D NumberRange struct.

func (*VectorRange) SetAll added in v0.10.0

func (ran *VectorRange) SetAll(value float64)

SetAll sets the minimum and maximum values of all components of the number range at the same time to the value passed.

func (*VectorRange) SetAxes added in v0.10.0

func (ran *VectorRange) SetAxes(x, y, z float64)

SetAxes sets the minimum and maximum values of all components of the number range at the same time. Both minimum and maximum boundaries of the NumberRange will be the same.

func (*VectorRange) SetRangeX added in v0.10.0

func (ran *VectorRange) SetRangeX(min, max float64)

SetRangeX sets the minimum and maximum values of the X component of the number range.

func (*VectorRange) SetRangeY added in v0.10.0

func (ran *VectorRange) SetRangeY(min, max float64)

SetRangeY sets the minimum and maximum values of the Y component of the number range.

func (*VectorRange) SetRangeZ added in v0.10.0

func (ran *VectorRange) SetRangeZ(min, max float64)

SetRangeZ sets the minimum and maximum values of the Z component of the number range.

func (*VectorRange) SetRanges added in v0.10.0

func (ran *VectorRange) SetRanges(min, max float64)

SetRanges sets the minimum and maximum values of all components (axes) of the number range.

func (VectorRange) Value added in v0.10.0

func (ran VectorRange) Value() Vector

Value returns a random value from within the bounds of the NumberRange.

type VertexInfo added in v0.9.0

type VertexInfo struct {
	ID                        int
	X, Y, Z                   float64
	U, V                      float64
	NormalX, NormalY, NormalZ float64
	Weights                   []float32
	Colors                    []Color
	ActiveColorChannel        int
	Bones                     []uint16
}

func NewVertex

func NewVertex(x, y, z, u, v float64) VertexInfo

NewVertex creates a new vertex information struct, which is used to create new Triangles. VertexInfo is purely for getting data into Meshes' vertex buffers, so after creating the Triangle, VertexInfos can be safely discarded (i.e. the VertexInfo doesn't hold "power" over the vertex it represents after creation).

type VertexSelection added in v0.9.0

type VertexSelection struct {
	Indices Set[int]
	Mesh    *Mesh
}

VertexSelection represents a selection of vertices on a Mesh.

func (*VertexSelection) ApplyMatrix added in v0.9.0

func (vs *VertexSelection) ApplyMatrix(matrix Matrix4)

ApplyMatrix applies a Matrix4 to the position of all vertices contained within the VertexSelection.

func (*VertexSelection) ForEachIndex added in v0.15.0

func (vs *VertexSelection) ForEachIndex(forEach func(index int))

ForEachIndex calls the provided function for each index selected in the VertexSelection.

func (*VertexSelection) Move added in v0.9.0

func (vs *VertexSelection) Move(x, y, z float64)

Move moves all vertices contained within the VertexSelection by the provided x, y, and z values.

func (*VertexSelection) MoveUVs added in v0.14.0

func (vs *VertexSelection) MoveUVs(dx, dy float64)

MoveUVs moves the UV values by the values specified.

func (*VertexSelection) MoveUVsVec added in v0.14.0

func (vs *VertexSelection) MoveUVsVec(vec Vector)

MoveUVsVec moves the UV values by the Vector values specified.

func (*VertexSelection) MoveVec added in v0.9.0

func (vs *VertexSelection) MoveVec(vec Vector)

Move moves all vertices contained within the VertexSelection by the provided 3D vector.

func (*VertexSelection) RotateUVs added in v0.14.0

func (vs *VertexSelection) RotateUVs(rotation float64)

RotateUVs rotates the UV values around the center of the UV values for the mesh in radians

func (*VertexSelection) SelectAll added in v0.9.0

func (vs *VertexSelection) SelectAll() *VertexSelection

SelectAll selects all vertices on the source Mesh.

func (*VertexSelection) SelectInChannel added in v0.10.0

func (vs *VertexSelection) SelectInChannel(channelIndex int) *VertexSelection

SelectInChannel selects all vertices in the Mesh that have a non-pure black color in the vertex color channel with the specified index. If the index lies outside of the bounds of currently existent color channels, the color channel will be created.

func (*VertexSelection) SelectIndices added in v0.15.0

func (vs *VertexSelection) SelectIndices(indices ...int) *VertexSelection

SelectIndices selects the passed indices in the Mesh belonging to the specified MeshPart.

func (*VertexSelection) SelectMaterialByName added in v0.15.0

func (vs *VertexSelection) SelectMaterialByName(materialNames ...string) *VertexSelection

SelectMaterialByName selects all vertices in the Mesh belonging to the specified material.

func (*VertexSelection) SelectMeshPart added in v0.9.0

func (vs *VertexSelection) SelectMeshPart(meshPart *MeshPart) *VertexSelection

SelectMeshPart selects all vertices in the Mesh belonging to the specified MeshPart.

func (*VertexSelection) SelectMeshPartByIndex added in v0.15.0

func (vs *VertexSelection) SelectMeshPartByIndex(indexNumber int) *VertexSelection

SelectMeshPartByIndex selects all vertices in the Mesh belonging to the specified MeshPart by index. If the MeshPart doesn't exist, this function will panic.

func (*VertexSelection) SetActiveColorChannel added in v0.9.0

func (vs *VertexSelection) SetActiveColorChannel(channelIndex int)

SetActiveColorChannel sets the active color channel in all vertices contained within the VertexSelection to the channel with the specified index.

func (*VertexSelection) SetColor added in v0.9.0

func (vs *VertexSelection) SetColor(channelIndex int, color Color)

SetColor sets the color of the specified channel in all vertices contained within the VertexSelection to the provided Color.

func (*VertexSelection) SetNormal added in v0.10.0

func (vs *VertexSelection) SetNormal(normal Vector)

SetNormal sets the normal of all vertices contained within the VertexSelection to the provided normal vector.

type World added in v0.10.0

type World struct {
	Name       string
	ClearColor Color // The clear color of the screen; note that this doesn't clear the color of the camera buffer or screen automatically;
	// this is just what the color is if the scene was exported using the Tetra3D addon from Blender. It's up to you as to how you'd like to
	// use it.
	FogColor Color   // The Color of any fog present in the Scene.
	FogMode  FogMode // The FogMode, indicating how the fog color is blended if it's on (not FogOff).
	// FogRange is the depth range at which the fog is active. FogRange consists of two numbers,
	// ranging from 0 to 1. The first indicates the start of the fog, and the second the end, in
	// terms of total depth of the near / far clipping plane. The default is [0, 1].
	FogOn           bool
	DitheredFogSize float32   // If greater than zero, how large the dithering effect is for transparent fog. If <= 0, dithering is disabled.
	FogRange        []float32 // The distances at which the fog is at 0% and 100%, respectively.
	FogCurve        int
	LightingOn      bool          // If lighting is enabled when rendering the scene.
	AmbientLight    *AmbientLight // Ambient lighting for this world
}

World represents a collection of settings that one uses to control lighting and ambience. This includes the screen clear color, fog color, mode, and range, whether lighting is globally enabled or not, and finally the ambient lighting level (using the World's AmbientLight).

func NewWorld added in v0.10.0

func NewWorld(name string) *World

NewWorld creates a new World with the specified name and default values for fog, lighting, etc).

func (*World) Clone added in v0.10.0

func (world *World) Clone() *World

Clone returns a new World with the same properties as the existing World.

Jump to

Keyboard shortcuts

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