graphics

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	White = ColorFromRGBA(255, 255, 255, 255)
	Black = ColorFromRGBA(0, 0, 0, 255)
)
View Source
var ErrUploadUnavailable = errors.New("graphics: resource is not resident after upload")

Functions

func AreaNits

func AreaNits(value float32, unit LightUnit, projectedArea float32) float32

AreaNits uses HDRP's projected area convention: pi*width*height for a rectangle, pi*pi*radius*radius for a disc, and 4*pi*length for a tube.

func BakeEnvironment

func BakeEnvironment[S RadianceSource](source S, width, samples int) (*image.NRGBA, error)

BakeEnvironment creates an RGBA8 atlas: six GGX reflection levels, one cosine-weighted diffuse level (irradiance / pi), and a split-sum BRDF LUT. RGBM stores linear radiance in [0,16]. This is asset-time work; the result is sampled directly at runtime with no per-frame convolution or allocation.

func BakeHDREnvironment

func BakeHDREnvironment[S RadianceSource](source S, width, samples int) (*image.NRGBA, error)

BakeHDREnvironment uses a separate exponent per texel, preserving dim colors beside bright light sources without normalizing the entire atlas. Its first seven tiles use RGBE; the BRDF tile remains linear RGBA8.

func DeviceFor

func DeviceFor(world *ecs.World) *render.Device

func GenerateTangents

func GenerateTangents(vertices []render.Vertex3D, indices []uint32, base uint32)

GenerateTangents averages UV derivatives over shared vertices, preserving mirrored UV handedness. It runs at asset creation; degenerate UVs stay zero. indices refer to vertices starting at base in the original vertex buffer.

func IntensityFromPhysical

func IntensityFromPhysical(value float32, unit LightUnit, measure, luxDistance float32) float32

IntensityFromPhysical is the inverse conversion used when changing units in an inspector. The caller supplies the light's solid angle or projected area.

func IsPreprocessedAtlas

func IsPreprocessedAtlas(data []byte) bool

IsPreprocessedAtlas reports whether data contains Onix's compiled atlas IR.

func LinearToSRGB

func LinearToSRGB(value float32) float32

func MarshalAtlas

func MarshalAtlas(metadata *AtlasMetadata) ([]byte, error)

MarshalAtlas encodes atlas metadata for allocation-light runtime loading.

func PreprocessAtlas

func PreprocessAtlas(data []byte) (compiled []byte, atlas bool, err error)

PreprocessAtlas compiles TexturePacker JSON when data is atlas metadata.

func PunctualCandela

func PunctualCandela(value float32, unit LightUnit, solidAngle, luxDistance float32) float32

PunctualCandela converts point/cone/pyramid inputs to luminous intensity. solidAngle is 4*pi for a point light or a spotlight without a reflector.

func SRGBToLinear

func SRGBToLinear(value float32) float32

SRGBToLinear and LinearToSRGB leave HDR values unclipped. Alpha is never transferred through these functions.

func SamplePanorama

func SamplePanorama[S LinearPanorama](p S, n mgl32.Vec3) mgl32.Vec3

SamplePanorama bilinearly samples an equirectangular panorama without allocating. Longitude wraps; latitude clamps at the poles.

func SetCurrentContext

func SetCurrentContext(ctx *Canvas2D)

SetCurrentContext selects an immediate canvas on the rendering thread.

func SetCurrentContextForTesting

func SetCurrentContextForTesting(ctx *Canvas2D) func()

func StraightRGBA8

func StraightRGBA8(src image.Image) *image.RGBA

StraightRGBA8 copies a decoded image into a straight-alpha RGBA8 buffer. Build tooling uses it so a compressed texture is encoded from exactly the bytes the runtime would have uploaded for the same source.

func TextureRevision

func TextureRevision() uint64

TextureRevision signals that per-texture dependencies may have changed. Content updates do not necessarily invalidate retained geometry.

func ValidateLightIntensity

func ValidateLightIntensity(value float32, unit LightUnit, units ...LightUnit) error

ValidateLightIntensity validates a value before converting it. EV100 is logarithmic: negative values are valid and zero EV does not turn a light off.

Types

type AlphaMode

type AlphaMode uint8
const (
	AlphaOpaque AlphaMode = iota
	AlphaMask
	AlphaBlend
)

type Atlas

type Atlas struct {
	*Texture
	// contains filtered or unexported fields
}

func NewAtlas

func NewAtlas(texture *Texture, metadata *AtlasMetadata) (*Atlas, error)

func (*Atlas) SubTexture

func (a *Atlas) SubTexture(name string) *Texture

type AtlasBounds

type AtlasBounds struct {
	X int `json:"x"`
	Y int `json:"y"`
	W int `json:"w"`
	H int `json:"h"`
}

type AtlasFrame

type AtlasFrame struct {
	Filename         string      `json:"filename"`
	Bounds           AtlasBounds `json:"frame"`
	SourceSize       AtlasSize   `json:"sourceSize"`
	SpriteSourceSize AtlasBounds `json:"spriteSourceSize"`
	Rotated          bool        `json:"rotated"`
}

type AtlasMeta

type AtlasMeta struct {
	Format string    `json:"format"`
	Image  string    `json:"image"`
	Size   AtlasSize `json:"size"`
}

type AtlasMetadata

type AtlasMetadata struct {
	Frames []AtlasFrame
	Meta   AtlasMeta
}

func ParseAtlas

func ParseAtlas(data []byte) (*AtlasMetadata, error)

func (*AtlasMetadata) Frame

func (m *AtlasMetadata) Frame(name string) (AtlasFrame, bool)

type AtlasSize

type AtlasSize struct {
	W int `json:"w"`
	H int `json:"h"`
}

type BoundingSphere

type BoundingSphere struct {
	Center mgl32.Vec3
	Radius float32
}

type Canvas2D

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

func Canvas2DContext

func Canvas2DContext(width, height int) *Canvas2D

func CanvasFor

func CanvasFor(world *ecs.World) *Canvas2D

func CurrentContext

func CurrentContext() *Canvas2D

CurrentContext is the immediate-mode canvas. ECS systems use CanvasFor(world).

func NewCanvas2D

func NewCanvas2D(device *render.Device, width, height int) *Canvas2D

func (*Canvas2D) BindMaterial2D

func (c *Canvas2D) BindMaterial2D(shader *Material2DShader)

func (*Canvas2D) BindTexture

func (c *Canvas2D) BindTexture(texture *Texture)

func (*Canvas2D) BlendSeparate

func (c *Canvas2D) BlendSeparate(rgb, alpha render.Blend)

func (*Canvas2D) BlendState

func (c *Canvas2D) BlendState() render.BlendState

BlendState returns the active component blending factors.

func (*Canvas2D) ClearColor

func (c *Canvas2D) ClearColor(clr ColorRGBA)

func (*Canvas2D) Device

func (c *Canvas2D) Device() *render.Device

func (*Canvas2D) DrawAffine

func (c *Canvas2D) DrawAffine(model, texture [6]float32, alpha float32)

DrawAffine submits a sprite using [a, b, tx, c, d, ty] 2D affine matrices.

func (*Canvas2D) DrawFrame

func (c *Canvas2D) DrawFrame()

func (*Canvas2D) DrawMatrices

func (c *Canvas2D) DrawMatrices(model mgl32.Mat4, texture mgl32.Mat3, alpha float32)

func (*Canvas2D) DrawMeshPickingTo

func (c *Canvas2D) DrawMeshPickingTo(target *render.RenderTarget, viewport render.Rect, clear render.RenderTargetClear, batch render.MeshBatch3D) error

DrawMeshPickingTo submits a uint32 ID phase to an offscreen picking target.

func (*Canvas2D) DrawMeshes

func (c *Canvas2D) DrawMeshes(batch render.MeshBatch3D) error

DrawMeshes flushes pending 2D work and submits a 3D render phase into the same frame. Callers control phase ordering by the order of submissions.

func (*Canvas2D) DrawMeshesTo

func (c *Canvas2D) DrawMeshesTo(target *render.RenderTarget, viewport render.Rect, clear render.RenderTargetClear, batch render.MeshBatch3D) error

DrawMeshesTo submits a 3D phase to an offscreen target, then restores the swapchain viewport and scissor used by subsequent canvas work.

func (*Canvas2D) DrawShapeAffine

func (c *Canvas2D) DrawShapeAffine(
	model, local [6]float32,
	width, height float32,
	kind render.ShapeKind,
	fill, border ColorRGBA,
	radius, borderWidth, alpha float32,
)

func (*Canvas2D) DrawShapeMatrices

func (c *Canvas2D) DrawShapeMatrices(
	model mgl32.Mat4,
	local mgl32.Mat3,
	width, height float32,
	kind render.ShapeKind,
	fill, border ColorRGBA,
	radius, borderWidth, alpha float32,
)

func (*Canvas2D) DrawTintedAffine

func (c *Canvas2D) DrawTintedAffine(model, texture [6]float32, tint ColorRGBA, alpha float32)

DrawTintedAffine submits a tinted sprite using [a, b, tx, c, d, ty] matrices.

func (*Canvas2D) DrawTintedMatrices

func (c *Canvas2D) DrawTintedMatrices(model mgl32.Mat4, texture mgl32.Mat3, tint ColorRGBA, alpha float32)

Keep the matrix entry direct so callers do not pay an adapter call per sprite.

func (*Canvas2D) DrawTintedMatricesCustom

func (c *Canvas2D) DrawTintedMatricesCustom(model mgl32.Mat4, texture mgl32.Mat3, tint ColorRGBA, alpha float32, custom [4][4]float32)

DrawTintedMatricesCustom submits a sprite with per-instance material data. The built-in HTML rounded-clip path stores its mask in custom2/custom3 while custom0/custom1 remain available to user Material2D shaders.

func (*Canvas2D) DrawTo

func (c *Canvas2D) DrawTo(target *render.RenderTarget, clear render.RenderTargetClear, draw func() error) (resultErr error)

DrawTo renders a logical 2D canvas into a target without starting another frame. Pending batches are flushed on both sides of the target boundary.

func (*Canvas2D) FinishFrame

func (c *Canvas2D) FinishFrame() error

func (*Canvas2D) PopClipRect

func (c *Canvas2D) PopClipRect()

func (*Canvas2D) ProjectionMatrix

func (c *Canvas2D) ProjectionMatrix() mgl32.Mat4

func (*Canvas2D) PushClipRect

func (c *Canvas2D) PushClipRect(x, y, width, height float32)

func (*Canvas2D) RasterScale

func (c *Canvas2D) RasterScale() float64

RasterScale returns the number of physical pixels represented by one logical canvas unit.

func (*Canvas2D) ResetProjectionMatrix

func (c *Canvas2D) ResetProjectionMatrix()

func (*Canvas2D) ResetViewMatrix

func (c *Canvas2D) ResetViewMatrix()

func (*Canvas2D) Resize

func (c *Canvas2D) Resize(width, height int)

func (*Canvas2D) RetainUntilFlush

func (canvas *Canvas2D) RetainUntilFlush[T comparable](value T)

RetainUntilFlush keeps a resource owner alive while its draw commands are queued on the CPU. Drivers retire submitted resources after GPU completion.

func (*Canvas2D) ScratchValue

func (c *Canvas2D) ScratchValue[Tag, T any]() *T

ScratchValue returns typed storage retained for the lifetime of the canvas.

func (*Canvas2D) SetBlendState

func (c *Canvas2D) SetBlendState(next render.BlendState)

SetBlendState flushes pending geometry before changing factors or constants.

func (*Canvas2D) SetMaterial2DParameters

func (c *Canvas2D) SetMaterial2DParameters(custom [4][4]float32)

func (*Canvas2D) SetProjectionMatrix

func (c *Canvas2D) SetProjectionMatrix(projection mgl32.Mat4)

func (*Canvas2D) SetRasterScale

func (c *Canvas2D) SetRasterScale(scale float64)

SetRasterScale sets the physical-pixel density used for rasterized 2D content while preserving the canvas' logical coordinate system.

func (*Canvas2D) SetViewMatrix

func (c *Canvas2D) SetViewMatrix(view mgl32.Mat4)

func (*Canvas2D) Size

func (c *Canvas2D) Size() (float32, float32)

func (*Canvas2D) ViewMatrix

func (c *Canvas2D) ViewMatrix() mgl32.Mat4

type ColorRGBA

type ColorRGBA struct {
	R float32
	G float32
	B float32
	A float32
}

func ColorFromRGB

func ColorFromRGB(r, g, b uint8) ColorRGBA

func ColorFromRGBA

func ColorFromRGBA(r, g, b, a uint8) ColorRGBA

func (ColorRGBA) GoColor

func (clr ColorRGBA) GoColor() color.RGBA

GoColor converts the color to a Go color.

func (ColorRGBA) Int32

func (clr ColorRGBA) Int32() int

Int32 converts the color to an integer.

func (ColorRGBA) Linear

func (color ColorRGBA) Linear() ColorRGBA

func (ColorRGBA) String

func (clr ColorRGBA) String() string

String converts the color to a string.

type CompressedTextureDescriptor

type CompressedTextureDescriptor struct {
	Width, Height int
	// Levels is the mip depth carried by the payload. Compressed textures
	// always ship a chain because a device cannot generate mips for block data.
	Levels int
	Format render.TextureFormat
	// Mipmap controls sampler filtering independently from the carried chain.
	Mipmap bool
	// Premultiplied reports colour channels already scaled by alpha, which the
	// encoder baked in and the runtime cannot recover.
	Premultiplied bool
	WrapU, WrapV  render.TextureAddressMode
}

CompressedTextureDescriptor describes a payload that is already in the texel layout the device samples. The build produces these; nothing at runtime re-encodes them.

type EnvironmentImages

type EnvironmentImages struct{ Panorama, Atlas *image.NRGBA }

EnvironmentImages keeps the visible panorama at its original resolution, independently of the lower-resolution GGX/diffuse/BRDF lighting atlas. Both images carry RGBE radiance; the atlas's BRDF tile is ordinary RGBA8.

func BakePanoramaEnvironment

func BakePanoramaEnvironment[S LinearPanorama](source S, width, samples int) (EnvironmentImages, error)

BakePanoramaEnvironment builds solid-angle-weighted radiance mips before convolution. A sample's PDF determines its footprint, preventing small HDR lights from becoming isolated bright pixels in rough reflection levels.

type Exposure

type Exposure struct {
	Mode         ExposureMode `json:"mode,omitempty"`
	EV100        float32      `json:"ev100,omitempty"`
	Compensation float32      `json:"compensation,omitempty"`
	Aperture     float32      `json:"aperture,omitempty"`
	ShutterSpeed float32      `json:"shutterSpeed,omitempty"` // seconds
	ISO          float32      `json:"iso,omitempty"`
}

Exposure applies to the entire lit scene, including emission, sky and IBL. The zero value uses fixed EV100 13. Explicit fixed mode permits EV100 zero.

func NewExposure

func NewExposure() Exposure

func (Exposure) Multiplier

func (e Exposure) Multiplier() float32

Multiplier uses HDRP's standard lens calibration (1 / (1.2 * 2^EV100)).

func (Exposure) Validate

func (e Exposure) Validate() error

func (Exposure) Value

func (e Exposure) Value() float32

type ExposureMode

type ExposureMode string
const (
	ExposureFixed    ExposureMode = "fixed"
	ExposurePhysical ExposureMode = "physical"
)

type FrameContext

type FrameContext struct {
	Canvas  *Canvas2D
	Uploads UploadQueue
}

FrameContext belongs to an ECS world/window. Engine systems obtain their canvas, device and upload queue here; immediate-mode globals do not select the destination of an ECS frame. BindFrame and uploads run on the render thread.

func BindFrame

func BindFrame(world *ecs.World, canvas *Canvas2D) *FrameContext

BindFrame installs or updates the world's explicit rendering destination. Rebinding the same canvas does not allocate or invalidate ECS resources.

func FrameFor

func FrameFor(world *ecs.World) *FrameContext

func (*FrameContext) AdvanceUploads

func (frame *FrameContext) AdvanceUploads(budget UploadBudget) (bool, error)

func (*FrameContext) Device

func (frame *FrameContext) Device() *render.Device

type ImageContainerDecoder

type ImageContainerDecoder interface {
	ImageFormatDecoder
	ImageContainerMagic() []byte
}

ImageContainerDecoder claims payloads by their leading bytes rather than by the extension they are addressed by.

A build packs platform-specific texture containers in place of the source image, so the same path carries either the source encoding or the container depending on how that platform was packed. The extension therefore no longer identifies the payload, and a decoder that owns a container magic is asked first.

type ImageDecoder

type ImageDecoder interface {
	DecodeImage([]byte, string, TextureOptions) (*Texture, error)
}

ImageDecoder decodes a scene image. Concrete implementations live in graphics/codec subpackages so unused image formats are not linked.

type ImageDecoderSet

type ImageDecoderSet[A, B, C, D, E ImageFormatDecoder] struct{}

ImageDecoderSet is a compile-time image format collection. It performs no registration and does not allocate while selecting a decoder.

func (ImageDecoderSet[A, B, C, D, E]) DecodeImage

func (ImageDecoderSet[A, B, C, D, E]) DecodeImage(data []byte, path string, options TextureOptions) (*Texture, error)

func (ImageDecoderSet[A, B, C, D, E]) DecodeImageContainer

func (ImageDecoderSet[A, B, C, D, E]) DecodeImageContainer(data []byte, options TextureOptions) (*Texture, error, bool)

type ImageDecoderWith

type ImageDecoderWith[Base ImageDecoder, Extra ImageFormatDecoder] struct{}

ImageDecoderWith extends a static collection with one additional format. Container magic takes precedence over the authored filename extension.

func (ImageDecoderWith[Base, Extra]) DecodeImage

func (ImageDecoderWith[Base, Extra]) DecodeImage(data []byte, name string, options TextureOptions) (*Texture, error)

func (ImageDecoderWith[Base, Extra]) DecodeImageContainer

func (ImageDecoderWith[Base, Extra]) DecodeImageContainer(data []byte, options TextureOptions) (*Texture, error, bool)

type ImageFormatDecoder

type ImageFormatDecoder interface {
	ImageExtension() string
	DecodeImage([]byte, TextureOptions) (*Texture, error)
}

ImageFormatDecoder decodes one filename extension in a static decoder set.

type LightUnit

type LightUnit string

LightUnit follows Unity HDRP's photometric input conventions. Distances and light dimensions are meters; shader RGB values are linear photometric values.

const (
	LightLumen   LightUnit = "lumen"
	LightCandela LightUnit = "candela"
	LightLux     LightUnit = "lux"
	LightNits    LightUnit = "nits"
	LightEV100   LightUnit = "ev100"
)

type LinearPanorama

type LinearPanorama interface {
	Size() (int, int)
	At(int, int) mgl32.Vec3
}

LinearPanorama supplies row-major linear RGB texels.

type Material2D

type Material2D interface {
	Material2D() Material2DData
}

type Material2DData

type Material2DData struct {
	Shader *Material2DShader
	Custom [4][4]float32
}

Material2DData is the per-instance data exposed to a custom 2D material.

type Material2DShader

type Material2DShader = shaderResource[render.Material2DShaderResource]

Material2DShader owns a user-defined sprite pipeline and recreates it when the installed render device changes.

func NewMaterial2DShader

func NewMaterial2DShader(descriptor render.ShaderDescriptor) (*Material2DShader, error)

type Material3D

type Material3D interface {
	Material3D() Material3DData
}

type Material3DData

type Material3DData struct {
	Shader                   *MeshShader
	BaseColorTexture         *Texture
	NormalTexture            *Texture
	MetallicRoughnessTexture *Texture
	Surface                  MaterialSurface
	Custom                   [4][4]float32
	Emissive                 ColorRGBA
	BaseColor                ColorRGBA
	EmissiveStrength         float32
	Metallic                 float32
	PerceptualRoughness      float32
	IOR                      float32
	AlphaCutoff              float32
	AlphaMode                AlphaMode
}

Material3DData is the fixed GPU-facing material contract shared by built-in and user-defined materials. Custom values map to shader inputs 11 through 14.

type MaterialSurface

type MaterialSurface struct {
	ClearcoatTexture          *Texture
	ClearcoatRoughnessTexture *Texture
	AnisotropyTexture         *Texture
	SheenRoughnessTexture     *Texture
	OcclusionTexture          *Texture
	EmissiveTexture           *Texture
	SpecularTexture           *Texture
	SheenColorTexture         *Texture
	ClearcoatNormalTexture    *Texture
	SpecularColorTexture      *Texture
	SheenColor                ColorRGBA
	SpecularColor             ColorRGBA
	AnisotropyStrength        float32
	NormalScale               float32
	AnisotropyRotation        float32 // radians in tangent space
	ClearcoatRoughness        float32
	OcclusionStrength         float32
	SheenRoughness            float32
	ClearcoatFactor           float32
	SpecularFactor            float32
	ClearcoatNormalScale      float32
	Unlit                     bool
	DoubleSided               bool
}

MaterialSurface contains glTF surface properties. Color factors are linear; color textures use sRGB and data textures use UNORM.

func NewMaterialSurface

func NewMaterialSurface() MaterialSurface

func (MaterialSurface) Textures

type Mesh

type Mesh struct {
	Vertices     []render.Vertex3D
	Indices      []uint32
	Submeshes    []Submesh
	Skin         []SkinVertex
	MorphTargets []MorphTarget

	Bounds BoundingSphere
	// contains filtered or unexported fields
}

Mesh is indexed triangle geometry using the same position/normal/UV/tangent layout consumed by Onix's 3D render pipelines. Geometry and static deformation streams must be set before the first upload; changing them requires a new mesh.

func CubeMesh

func CubeMesh(size float32) *Mesh

func NewMesh

func NewMesh(vertices []render.Vertex3D, indices []uint32) (*Mesh, error)

func NewMeshOwned

func NewMeshOwned(vertices []render.Vertex3D, indices []uint32) (*Mesh, error)

NewMeshOwned constructs a mesh by taking ownership of vertices and indices. Callers must not retain or mutate either slice after a successful call.

func PlaneMesh

func PlaneMesh(size float32) *Mesh

func UVSphereMesh

func UVSphereMesh(radius float32, sectors, stacks int) *Mesh

func (*Mesh) DeformVertices

func (m *Mesh) DeformVertices(dst []render.Vertex3D, morphWeights []float32, jointMatrices []mgl32.Mat4) ([]render.Vertex3D, error)

DeformVertices applies morph targets and linear-blend skinning into dst. Reusing dst with enough capacity makes subsequent calls allocation-free.

func (*Mesh) Dispose

func (m *Mesh) Dispose() error

func (*Mesh) GPUDeformationData

func (m *Mesh) GPUDeformationData() ([]render.MeshSkinVertex, []render.MeshMorphVertex, error)

GPUDeformationData returns cached renderer-neutral skin and morph streams. The returned slices remain owned by the mesh and are valid until Dispose.

func (*Mesh) RenderHandle

func (m *Mesh) RenderHandle() render.MeshHandle

func (*Mesh) RenderHandleFor

func (m *Mesh) RenderHandleFor(device *render.Device) render.MeshHandle

func (*Mesh) UploadError

func (m *Mesh) UploadError() error

type MeshShader

type MeshShader = shaderResource[render.MeshShaderResource]

MeshShader owns a user-defined 3D shader and recreates its native pipeline when the installed render device changes.

func NewMeshShader

func NewMeshShader(descriptor render.ShaderDescriptor) (*MeshShader, error)

type MorphTarget

type MorphTarget struct {
	Name          string
	PositionDelta [][3]float32
	NormalDelta   [][3]float32
	TangentDelta  [][3]float32
}

MorphTarget stores imported position/normal/tangent deltas. Rendering backends may opt into applying these deltas without changing indexed base geometry or the mesh upload ABI.

type NoImageDecoder

type NoImageDecoder struct{}

NoImageDecoder fills an unused slot in ImageDecoderSet.

func (NoImageDecoder) DecodeImage

func (NoImageDecoder) DecodeImage(_ []byte, _ TextureOptions) (*Texture, error)

func (NoImageDecoder) ImageExtension

func (NoImageDecoder) ImageExtension() string

type PanoramaRadiance

type PanoramaRadiance struct{ Image image.Image }

PanoramaRadiance interprets a conventional sRGB equirectangular image.

func (PanoramaRadiance) Radiance

func (p PanoramaRadiance) Radiance(n mgl32.Vec3) mgl32.Vec3

type RadianceSource

type RadianceSource interface{ Radiance(mgl32.Vec3) mgl32.Vec3 }

RadianceSource supplies linear HDR radiance along a world-space direction. BakeEnvironment evaluates the concrete source without interface dispatch.

type Resource

type Resource[T any] struct {
	Data  T
	Usage ResourceUsage
}

func NewResource

func NewResource[T any](data T, usage ResourceUsage) Resource[T]

type ResourceUsage

type ResourceUsage uint8
const (
	ResourceUsageCPU ResourceUsage = 1 << iota
	ResourceUsageGPU
	ResourceUsageDefault = ResourceUsageCPU | ResourceUsageGPU
)

func (ResourceUsage) Has

func (u ResourceUsage) Has(flag ResourceUsage) bool

type SkinVertex

type SkinVertex struct {
	Joints  [4]uint32
	Weights [4]float32
	Active  bool
}

type SkyRadiance

type SkyRadiance struct{ Zenith, Horizon, Ground mgl32.Vec3 }

SkyRadiance is an analytic daylight source for projects without a panorama. Sun radiance belongs to the directional light; excluding a disk here avoids counting it twice in the environment's diffuse illumination.

func (SkyRadiance) Radiance

func (sky SkyRadiance) Radiance(n mgl32.Vec3) mgl32.Vec3

type StandardMaterial

type StandardMaterial struct {
	MetallicRoughnessTexture *Texture
	Shader                   *MeshShader
	BaseColorTexture         *Texture
	NormalTexture            *Texture
	Surface                  MaterialSurface
	Emissive                 ColorRGBA
	BaseColor                ColorRGBA
	EmissiveStrength         float32 // unitless multiplier, defaults to 1
	Metallic                 float32
	PerceptualRoughness      float32
	IOR                      float32 // index of refraction; 0 means positive infinity
	AlphaCutoff              float32
	AlphaMode                AlphaMode
}

StandardMaterial uses metallic/roughness PBR. Emissive is linear RGB in nits before EmissiveStrength. Construct it with NewStandardMaterial for defaults.

func NewStandardMaterial

func NewStandardMaterial(color ColorRGBA) *StandardMaterial

func (StandardMaterial) Material3D

func (m StandardMaterial) Material3D() Material3DData

func (*StandardMaterial) SetEmission

func (m *StandardMaterial) SetEmission(color ColorRGBA, intensity float32, unit LightUnit) error

SetEmission sets the emissive color using HDRP luminance units. A white color with intensity 100 nits emits linear RGB (100,100,100) before exposure. It resets EmissiveStrength to 1 so the requested intensity is exact. This does not turn a mesh into a light source for other objects.

type Submesh

type Submesh struct {
	FirstIndex uint32
	IndexCount uint32
	Material   uint32
	Node       int32
}

Submesh selects one material and an optional animated rigid node. Node is -1 for skinned geometry or geometry without a node transform.

type Texture

type Texture struct {
	Width int

	OffsetX      int
	SourceHeight int

	SourceWidth int
	Height      int

	OffsetY int

	MaxV float32

	U, V  float32
	Angle float32
	MaxU  float32
	// contains filtered or unexported fields
}

func CreateEmptyTexture

func CreateEmptyTexture(width, height int, format render.TextureFormat, usage ResourceUsage) *Texture

CreateEmptyTexture creates a zero-filled, single-level texture. Its CPU shadow grows only through the last updated texel; the untouched suffix remains zero. Device recreation expands this compact shadow into a temporary upload payload. GPU storage is created on first use, including any pending region updates.

func CreateTextureByColor

func CreateTextureByColor(clr ColorRGBA) *Texture

func CreateTextureByImageNoMipmap

func CreateTextureByImageNoMipmap(im *image.RGBA) *Texture

func CreateTextureByImageWithUsage

func CreateTextureByImageWithUsage(im *image.RGBA, mipmap bool, usage ResourceUsage) *Texture

func CreateTextureBySharedImage

func CreateTextureBySharedImage(im *image.RGBA, mipmap bool, usage ResourceUsage) *Texture

CreateTextureBySharedImage shares a tightly packed image's pixels with the texture's CPU shadow. Other image layouts are copied. The caller must synchronize image writes with texture use and call UpdateRegions after edits. Resizing requires a new texture and a separate pixel buffer for the old one.

func CreateTextureFromExternal

func CreateTextureFromExternal(descriptor render.ExternalTextureDescriptor) (*Texture, error)

CreateTextureFromExternal imports a platform-owned surface without copying pixels through Go memory. The active render driver must implement render.ExternalTextureDriver.

func CreateTextureFromRenderTarget

func CreateTextureFromRenderTarget(target *render.RenderTarget) (*Texture, error)

CreateTextureFromRenderTarget exposes a target color attachment to 2D/UI rendering without transferring ownership of the attachment. Construction is CPU-only; RenderHandleFor realizes the attachment on the supplied device.

func CreateTextureR8

func CreateTextureR8(width, height int, pixels []byte, mipmap bool, usage ResourceUsage) *Texture

CreateTextureR8 creates a single-channel unorm texture. The pixel slice is retained for device recreation when usage includes ResourceUsageCPU.

func NewSubTexture

func NewSubTexture(parent *Texture, width, height int, u, v, maxU, maxV, angle float32) *Texture

func TextureFromCompressed

func TextureFromCompressed(descriptor CompressedTextureDescriptor, pixels []byte) (*Texture, error)

TextureFromCompressed adopts a prebuilt block-compressed payload. The caller transfers ownership of pixels, which must hold the complete mip chain.

The texture is created GPU-only: compressed blocks cannot be read back or partially updated, so retaining a CPU copy would only waste memory.

func TextureFromImage

func TextureFromImage(src image.Image, options TextureOptions) *Texture

TextureFromImage converts a decoded image into a texture.

func TextureFromOwnedDecodedImage

func TextureFromOwnedDecodedImage(src image.Image, options TextureOptions) *Texture

TextureFromOwnedDecodedImage takes ownership of a decoder's image buffer. RGBA and NRGBA images use their pixels in place when tightly packed; other image formats are converted into the texture's RGBA storage.

func TextureFromOwnedImage

func TextureFromOwnedImage(src *image.RGBA, options TextureOptions) *Texture

TextureFromOwnedImage transfers an RGBA image buffer into a texture.

func TextureFromOwnedNRGBA

func TextureFromOwnedNRGBA(src *image.NRGBA, options TextureOptions) *Texture

TextureFromOwnedNRGBA transfers a straight-alpha NRGBA buffer into a texture.

func (*Texture) AddressModes

AddressModes reports the sampler addressing shared by all views of a texture.

func (*Texture) BatchKey

func (t *Texture) BatchKey() uint64

func (*Texture) ContentRevision

func (t *Texture) ContentRevision() uint64

ContentRevision is shared by atlas views of the same backing texture.

func (*Texture) Dispose

func (t *Texture) Dispose() error

func (*Texture) DynamicContent

func (t *Texture) DynamicContent() bool

DynamicContent identifies textures produced outside the retained paint lifecycle. Their consumers must be redrawn even without component writes.

func (*Texture) Format

func (t *Texture) Format() render.TextureFormat

Format reports the texture's texel layout.

func (*Texture) GeometryRevision

func (t *Texture) GeometryRevision() uint64

GeometryRevision changes when logical bounds or resource lifetime change. Pixel updates preserve this revision, including external surface refreshes.

func (*Texture) LogicalHeight

func (t *Texture) LogicalHeight() int

func (*Texture) LogicalWidth

func (t *Texture) LogicalWidth() int

func (*Texture) MipLevels

func (t *Texture) MipLevels() int

MipLevels reports the depth the uploaded texture will have. It differs from payloadLevels for uncompressed textures, whose chain the device builds.

func (*Texture) Mipmapped

func (t *Texture) Mipmapped() bool

func (*Texture) PremultipliedAlpha

func (t *Texture) PremultipliedAlpha() bool

func (*Texture) RasterScale

func (t *Texture) RasterScale() (x, y float32)

RasterScale returns the physical pixels represented by one logical texture unit.

func (*Texture) RefreshExternal

func (t *Texture) RefreshExternal() error

RefreshExternal marks a newly produced version of an imported surface ready for rendering. The native texture handle and graphics.Texture remain stable.

func (*Texture) RenderHandle

func (t *Texture) RenderHandle() render.TextureHandle

func (*Texture) RenderHandleFor

func (t *Texture) RenderHandleFor(device *render.Device) render.TextureHandle

func (*Texture) SetLogicalSize

func (t *Texture) SetLogicalSize(width, height int)

SetLogicalSize records the layout size of a higher-resolution texture. Unlike SetSourceRect, it preserves the complete texture as drawable content.

func (*Texture) SetSourceRect

func (t *Texture) SetSourceRect(width, height, offsetX, offsetY int)

SetSourceRect records the untrimmed logical size and the trimmed frame offset. Atlas formats use this information to draw packed sprites without stretching the cropped pixels across the original sprite bounds.

func (*Texture) Trimmed

func (t *Texture) Trimmed() bool

func (*Texture) UpdateRegions

func (t *Texture) UpdateRegions(updates []TextureRegionUpdate)

func (*Texture) UploadError

func (t *Texture) UploadError() error

func (*Texture) Valid

func (t *Texture) Valid() bool

func (*Texture) ValidFor

func (t *Texture) ValidFor(device *render.Device) bool

type TextureOptions

type TextureOptions struct {
	// SRGB applies to color images, never normal or material data maps.
	SRGB             bool
	WrapU, WrapV     render.TextureAddressMode
	Mipmap           bool
	PremultiplyAlpha bool
	Usage            ResourceUsage
}

type TextureRegionUpdate

type TextureRegionUpdate struct {
	Pixels []byte
	X      int
	Y      int
	Width  int
	Height int
}

type ToneMapping

type ToneMapping string

ToneMapping selects a display curve for exposed linear scene radiance. The zero value uses Reinhard. ACES uses the color transforms and RRT/ODT fit of ACESFilmicToneMapping.

const (
	ToneMappingReinhard ToneMapping = "reinhard"
	ToneMappingACES     ToneMapping = "aces"
)

func (ToneMapping) Validate

func (t ToneMapping) Validate() error

type UploadBudget

type UploadBudget struct {
	Time      time.Duration
	Bytes     int64
	Resources int
}

UploadBudget limits work started in one Advance call. Time is checked between resources: a single driver call cannot be interrupted. An oversized resource is allowed as the first unit to guarantee progress. Non-positive Time performs one unit; non-positive Bytes and Resources impose no additional limit.

type UploadQueue

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

UploadQueue deduplicates CPU-ready assets. All methods belong to the render thread, and all uploads use the explicitly supplied device.

func (*UploadQueue) AddMaterial2DShader

func (q *UploadQueue) AddMaterial2DShader(shader *Material2DShader)

func (*UploadQueue) AddMaterial3D

func (q *UploadQueue) AddMaterial3D(material Material3DData)

func (*UploadQueue) AddMesh

func (q *UploadQueue) AddMesh(mesh *Mesh)

func (*UploadQueue) AddMeshShader

func (q *UploadQueue) AddMeshShader(shader *MeshShader)

func (*UploadQueue) AddTexture

func (q *UploadQueue) AddTexture(texture *Texture)

func (*UploadQueue) Advance

func (q *UploadQueue) Advance(device *render.Device, budget UploadBudget) (bool, error)

func (*UploadQueue) ReadyFor

func (q *UploadQueue) ReadyFor(device *render.Device) bool

func (*UploadQueue) Remaining

func (q *UploadQueue) Remaining() int

func (*UploadQueue) Reset

func (q *UploadQueue) Reset()

Reset releases references and retains storage for the next preparation.

Directories

Path Synopsis
codec
gif
hdr
Package hdr decodes Radiance RGBE panoramas without reducing their dynamic range.
Package hdr decodes Radiance RGBE panoramas without reducing their dynamic range.
ontex
Package ontex reads and writes the ONIXTEX1 container: a block-compressed texture together with the mip chain the build already generated.
Package ontex reads and writes the ONIXTEX1 container: a block-compressed texture together with the mip chain the build already generated.
png
svg
ultrahdr
Package ultrahdr reconstructs linear HDR from JPEG base images and gain maps.
Package ultrahdr reconstructs linear HDR from JPEG base images and gain maps.

Jump to

Keyboard shortcuts

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