vphong

package
v2.0.0-dev0.0.30 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2023 License: BSD-3-Clause Imports: 17 Imported by: 2

README

vPhong is a Blinn-Phong rendering system in vGPU

Blinn-Phong is a standard lighting model that used to be built into OpenGL, and is widely used in 3D graphics: wikipedia Blinn-Phong, learnopengl.com.

Supports 4 different types of lights, with a max of 8 instances of each light type:

  • Ambient: light emitted from everywhere -- provides a background of diffuse light bouncing around in all directions.

  • Directional: light directed along a given vector (specified as a position of a light shining toward the origin), with no attenuation. This is like the sun.

  • Point: an omnidirectional light with a position and associated decay factors, which divide the light intensity as a function of linear and quadratic distance. The quadratic factor dominates at longer distances.light radiating out in all directdions from a specific point,

  • Spot: a light with a position and direction and associated decay factors and angles, which divide the light intensity as a function of linear and quadratic distance. The quadratic factor dominates at longer distances.

Meshes are indexed triangles.

There are 3 rendering pipelines:

  • Texture: color comes from texture image
  • OneColor: a single color for the entire mesh.
  • PerVertex: color is provided per vertex by the mesh.

The color model has the following factors:

  • Color = main color of surface arising from one of the 3 sources listed above, used for both ambient and diffuse color in standard Phong model -- alpha component determines transparency -- note that transparent objects require more complex rendering, to sort objects as a function of depth.
  • Emissive = color that surface emits independent of any lighting -- i.e., glow -- can be used for marking lights with an object.
  • Shiny = specular shininess factor -- how focally the surface shines back directional light -- this is an exponential factor, with 0 = very broad diffuse reflection, and higher values (typically max of 128) having a smaller more focal specular reflection. Default is 30.
  • Reflect = reflectiveness of the surface in the region where specular reflected light is emitted -- 1 for full shiny white reflection (specular) color, 0 = no shine reflection. The specular color is always set to white, which will reflect the light color accurately.
  • Bright = overall multiplier on final computed color value -- can be used to tune the overall brightness of various surfaces relative to each other for a given set of lighting parameters.

Known Issues

There must be at least one texture image, otherwise the Mac VKMolten system triggers this error. The system automatically adds a dummy image to deal with this.

[mvk-error] VK_ERROR_INVALID_SHADER_NV: Unable to convert SPIR-V to MSL:
MSL conversion error: Unsized array of images is not supported in MSL.

Layout of Vars

Set: -2
    Role: Vertex
        Var: 0:	Pos	Float32Vec3	(size: 12)	Vals: 6
        Var: 1:	Norm	Float32Vec3	(size: 12)	Vals: 6
        Var: 2:	Tex	Float32Vec2	(size: 8)	Vals: 6
        Var: 3:	Color	Float32Vec4	(size: 16)	Vals: 6
    Role: Index
        Var: 4:	Index	Uint32	(size: 4)	Vals: 6
Set: -1
    Role: Push
        Var: 0:	PushU	Struct	(size: 128)	Vals: 1
Set: 0
    Role: Uniform
        Var: 0:	Mtxs	Struct	(size: 128)	Vals: 1
Set: 1
    Role: Uniform
        Var: 0:	NLights	Struct	(size: 16)	Vals: 1
Set: 2
    Role: Uniform
        Var: 0:	AmbLights	Struct[8]	(size: 16)	Vals: 1
        Var: 1:	DirLights	Struct[8]	(size: 32)	Vals: 1
        Var: 2:	PointLights	Struct[8]	(size: 48)	Vals: 1
        Var: 3:	SpotLights	Struct[8]	(size: 64)	Vals: 1
Set: 3
    Role: TextureRole
        Var: 0:	Tex	ImageRGBA32	(size: 4)	Vals: 3

Documentation

Index

Constants

View Source
const MaxLights = 8

MaxLights is upper limit on number of any given type of light

Variables

This section is empty.

Functions

func CameraViewMat

func CameraViewMat(pos, target, up mat32.Vec3) *mat32.Mat4

CameraViewMat returns the camera view matrix, based position of camera facing at target position, with given up vector.

Types

type AmbientLight

type AmbientLight struct {

	// color of light -- multiplies ambient color of materials
	Color mat32.Vec3
	// contains filtered or unexported fields
}

AmbientLight provides diffuse uniform lighting -- typically only one of these

type Colors

type Colors struct {

	// main color of surface, used for both ambient and diffuse color in standard Phong model -- alpha component determines transparency -- note that transparent objects require more complex rendering
	Color mat32.Vec4

	// X = shininess spread factor, Y = shine reflection factor, Z = brightness factor:  shiny = specular shininess factor -- how focally the surface shines back directional light -- this is an exponential factor, with 0 = very broad diffuse reflection, and higher values (typically max of 128) having a smaller more focal specular reflection.  Shine reflect = 1 for full shine white reflection (specular) color, 0 = no shine reflection.  bright = overall multiplier on final computed color value -- can be used to tune the overall brightness of various surfaces relative to each other for a given set of lighting parameters.  W is used for Tex idx.
	ShinyBright mat32.Vec4

	// color that surface emits independent of any lighting -- i.e., glow -- can be used for marking lights with an object
	Emissive mat32.Vec4
}

Colors are the material colors with padding for direct uploading to shader

func NewColors

func NewColors(clr, emis color.Color, shiny, reflect, bright float32) *Colors

NewGoColor sets the colors from standard Go colors

func (*Colors) SetColors

func (cl *Colors) SetColors(clr, emis color.Color, shiny, reflect, bright float32)

SetColors sets the colors from standard Go colors

type CurRender

type CurRender struct {

	// index of descriptor collection to use -- for threaded / parallel rendering -- see vgup.Vars NDescs for more info
	DescIdx int

	// a texture was selected -- if true, overrides other options
	UseTexture bool

	// a per-vertex color was selected
	UseVtxColor bool

	// current model pose matrix
	ModelMtx mat32.Mat4

	// camera view and projection matrixes
	VPMtx Mtxs

	// current color surface properties
	Color Colors

	// texture parameters -- repeat, offset
	TexPars TexPars

	// index of currently-selected texture
	TexIdx int
}

CurRender holds info about the current render as updated by Use* methods -- determines which pipeline is used. Default is single color.

func (*CurRender) NewPush

func (cr *CurRender) NewPush() *PushU

NewPush generates a new Push object based on current render settings unsafe.Pointer does not work having this be inside the CurRender obj itself so we create one afresh.

type DirLight

type DirLight struct {

	// color of light at full intensity
	Color mat32.Vec3

	// position of light vector -- think of it shining down from this position toward the origin, i.e., the negation of this position is the vector.
	Pos mat32.Vec3
	// contains filtered or unexported fields
}

DirLight is directional light, which is assumed to project light toward the origin based on its position, with no attenuation, like the Sun. For rendering, the position is negated and normalized to get the direction vector (i.e., absolute distance doesn't matter)

type Mesh

type Mesh struct {

	// number of vertex points, as mat32.Vec3 -- always includes mat32.Vec3 normals and mat32.Vec2 texture coordinates
	NVtx int

	// number of indexes, as mat32.ArrayU32
	NIdx int

	// has per-vertex colors, as mat32.Vec4 per vertex
	HasColor bool
}

Mesh records the number of elements in an indexed triangle mesh, which always includes normals and texture coordinates, and optionally per-vertex colors.

type Mtxs

type Mtxs struct {

	// View Matrix: transforms world into camera-centered, 3D coordinates
	View mat32.Mat4

	// Projection Matrix: transforms camera coords into 2D render coordinates
	Prjn mat32.Mat4
}

Mtxs contains the camera view and projection matricies, for uniform uploading

type NLights

type NLights struct {
	Ambient int32
	Dir     int32
	Point   int32
	Spot    int32
}

Number of different lights active

func (*NLights) Reset

func (nl *NLights) Reset()

type Phong

type Phong struct {

	// number of each type of light
	NLights NLights

	// ambient lights
	Ambient [MaxLights]AmbientLight

	// directional lights
	Dir [MaxLights]DirLight

	// point lights
	Point [MaxLights]PointLight

	// spot lights
	Spot [MaxLights]SpotLight

	// render using wireframe instead of filled polygons -- this must be set prior to configuring the Phong rendering system
	Wireframe bool `def:"false"`

	// state for current rendering
	Cur CurRender

	// meshes -- holds all the mesh data -- must be configured prior to rendering
	Meshes ordmap.Map[string, *Mesh]

	// textures -- must be configured prior to rendering -- a maximum of 16 textures is supported for full cross-platform portability
	Textures ordmap.Map[string, *Texture]

	// colors, optionally available for looking up by name -- not used directly in rendering
	Colors ordmap.Map[string, *Colors]

	// rendering system
	Sys vgpu.System

	// mutex on updating
	UpdtMu sync.Mutex `view:"-" copy:"-" json:"-" xml:"-"`
}

Phong implements standard Blinn-Phong rendering pipelines in a vgpu System. Must Add all Lights, Meshes, Colors, Textures first, and call Config() to configure everything prior to first RenderStart.

Meshes are configured initially with numbers of points, then after Config(), points are set by calling MeshFloatsBy* and assigning values.

If any changes are made to numbers or sizes of anything, you must call Config() again.

Changes to data only can be synced by calling Sync()

Rendering starts with RenderStart, followed by Use* calls to specify the parameters for each item, and then a Draw call to add the rendering command, followed by RenderEnd.

func (*Phong) AddAmbientLight

func (ph *Phong) AddAmbientLight(color mat32.Vec3)

AddAmbientLight adds Ambient light at given position

func (*Phong) AddColor

func (ph *Phong) AddColor(name string, clr *Colors)

AddColor adds to list of colors, which can be use for a materials library

func (*Phong) AddDirLight

func (ph *Phong) AddDirLight(color, pos mat32.Vec3)

AddDirLight adds directional light

func (*Phong) AddMesh

func (ph *Phong) AddMesh(name string, nVtx, nIdx int, hasColor bool)

AddMesh adds a Mesh with name and given number of verticies, indexes, and optional per-vertex color

func (*Phong) AddPointLight

func (ph *Phong) AddPointLight(color, pos mat32.Vec3, linDecay, quadDecay float32)

AddPointLight adds point light. Defaults: linDecay=.1, quadDecay=.01

func (*Phong) AddSpotLight

func (ph *Phong) AddSpotLight(color, pos, dir mat32.Vec3, angDecay, cutAngle, linDecay, quadDecay float32)

AddSpotLight adds spot light Defaults: angDecay=15, cutAngle=45 (max 90), linDecay=.01, quadDecay=0.001

func (*Phong) AddTexture

func (ph *Phong) AddTexture(name string, tex *Texture)

AddTexture adds to list of textures

func (*Phong) AllocTextures

func (ph *Phong) AllocTextures()

AllocTextures allocates textures that have been previously configured, via ConfigTextures(), after Phong.Sys.Config() has been called.

func (*Phong) Config

func (ph *Phong) Config()

Config configures everything after everything has been Added

func (*Phong) ConfigLights

func (ph *Phong) ConfigLights()

ConfigLights configures the rendering for the lights that have been added.

func (*Phong) ConfigMeshes

func (ph *Phong) ConfigMeshes()

ConfigMeshes configures vals for meshes -- this is the first of two passes in configuring and setting mesh values -- Phong.Sys.Config is called after this method (and everythign else is configured).

func (*Phong) ConfigMeshesTextures

func (ph *Phong) ConfigMeshesTextures()

ConfigMeshesTextures configures the Meshes and Textures based on everything added in the Phong config, prior to Sys.Config() which does host allocation.

func (*Phong) ConfigPipeline

func (ph *Phong) ConfigPipeline(pl *vgpu.Pipeline)

ConfigPipeline configures graphics settings on the pipeline

func (*Phong) ConfigSys

func (ph *Phong) ConfigSys()

ConfigSys configures the vDraw System and pipelines.

func (*Phong) ConfigTextures

func (ph *Phong) ConfigTextures()

ConfigTextures configures vals for textures -- this is the first of two passes -- call Phong.Sys.Config after everything is config'd. This automatically allocates images by size so everything fits within the MaxTexturesPerStage limit, as texture arrays.

func (*Phong) DeleteMesh

func (ph *Phong) DeleteMesh(name string)

DeleteMesh deletes Mesh with name

func (*Phong) DeleteTexture

func (ph *Phong) DeleteTexture(name string)

DeleteTexture deletes texture with name

func (*Phong) Destroy

func (ph *Phong) Destroy()

func (*Phong) MeshFloatsByIdx

func (ph *Phong) MeshFloatsByIdx(i int) (pos, norm, tex, clr mat32.ArrayF32, idx mat32.ArrayU32)

MeshFloatsByIdx returns the mat32.ArrayF32's and mat32.ArrayU32 for given mesh for assigning values to the mesh. Must call ModMeshByIdx after setting these values to mark as modified.

func (*Phong) MeshFloatsByName

func (ph *Phong) MeshFloatsByName(name string) (pos, norm, tex, clr mat32.ArrayF32, idx mat32.ArrayU32)

MeshFloatsByName returns the mat32.ArrayF32's and mat32.ArrayU32 for given mesh for assigning values to the mesh. Must call ModMeshByName after setting these values to mark as modified.

func (*Phong) ModMeshByIdx

func (ph *Phong) ModMeshByIdx(i int)

ModMeshByIdx marks given mesh by index as modified. Must call after modifying mesh values, to mark for syncing

func (*Phong) ModMeshByName

func (ph *Phong) ModMeshByName(name string)

ModMeshByName marks given mesh by name as modified. Must call after modifying mesh values, to mark for syncing

func (*Phong) Push

func (ph *Phong) Push(pl *vgpu.Pipeline, push *PushU)

Push pushes given push constant data

func (*Phong) Render

func (ph *Phong) Render()

Render does one step of rendering given current Use* settings

func (*Phong) RenderOnecolor

func (ph *Phong) RenderOnecolor()

RenderOnecolor renders current settings to onecolor pipeline

func (*Phong) RenderTexture

func (ph *Phong) RenderTexture()

RenderTexture renders current settings to texture pipeline

func (*Phong) RenderVtxColor

func (ph *Phong) RenderVtxColor()

RenderVtxColor renders current settings to vertexcolor pipeline

func (*Phong) ResetMeshes

func (ph *Phong) ResetMeshes()

ResetMeshes resets the meshes for reconfiguring

func (*Phong) ResetNLights

func (ph *Phong) ResetNLights()

ResetNLights resets number of lights to 0 -- for reconfig

func (*Phong) ResetTextures

func (ph *Phong) ResetTextures()

ResetTextures resets all textures

func (*Phong) SetAmbientLight

func (ph *Phong) SetAmbientLight(idx int, color mat32.Vec3)

SetAmbientLight sets Ambient light at index to given position

func (*Phong) SetDirLight

func (ph *Phong) SetDirLight(idx int, color, pos mat32.Vec3)

SetDirLight sets directional light at given index

func (*Phong) SetModelMtx

func (ph *Phong) SetModelMtx(model *mat32.Mat4)

SetModelMtx sets the model pose matrix -- must be set per render step (otherwise last one will be used)

func (*Phong) SetPointLight

func (ph *Phong) SetPointLight(idx int, color, pos mat32.Vec3, linDecay, quadDecay float32)

SetPointLight sets point light at given index. Defaults: linDecay=.1, quadDecay=.01

func (*Phong) SetSpotLight

func (ph *Phong) SetSpotLight(idx int, color, pos, dir mat32.Vec3, angDecay, cutAngle, linDecay, quadDecay float32)

SetSpotLight sets spot light at given index Defaults: angDecay=15, cutAngle=45 (max 90), linDecay=.01, quadDecay=0.001

func (*Phong) SetViewPrjn

func (ph *Phong) SetViewPrjn(view, prjn *mat32.Mat4)

SetViewPrjn sets the camera view and projection matrixes, and updates uniform data, so they are ready to use.

func (*Phong) Sync

func (ph *Phong) Sync()

Sync synchronizes any changes in val data up to GPU device memory. any changes in numbers or sizes of any element requires a Config call.

func (*Phong) UpdateTextureIdx

func (ph *Phong) UpdateTextureIdx(idx int) error

UpdateTextureIdx updates texture by index -- call this when the underlying image changes. Assumes the size remains the same. Must Sync for the changes to take effect.

func (*Phong) UpdateTextureName

func (ph *Phong) UpdateTextureName(name string) error

UpdateTextureName updates texture by name

func (*Phong) UseColor

func (ph *Phong) UseColor(clr, emis color.Color, shiny, reflect, bright float32)

UseColors sets the color values for current render step

func (*Phong) UseColorIdx

func (ph *Phong) UseColorIdx(idx int) error

UseColorIdx selects color by index for current render step

func (*Phong) UseColorName

func (ph *Phong) UseColorName(name string) error

UseColorName selects color by name for current render step

func (*Phong) UseFullTexture

func (ph *Phong) UseFullTexture()

UseFullTexture sets the texture parameters for the next render command: to render the full texture: repeat = 1,1; off = 0,0

func (*Phong) UseMeshIdx

func (ph *Phong) UseMeshIdx(idx int) error

UseMeshIdx selects mesh by index for current render step. If mesh has per-vertex colors, these are selected for rendering, and texture is turned off. UseTexture* after this to override.

func (*Phong) UseMeshName

func (ph *Phong) UseMeshName(name string) error

UseMeshName selects mesh by name for current render step If mesh has per-vertex colors, these are selected for rendering, and texture is turned off. UseTexture* after this to override.

func (*Phong) UseNoTexture

func (ph *Phong) UseNoTexture()

UseNoTexture turns off texture rendering

func (*Phong) UseTextureIdx

func (ph *Phong) UseTextureIdx(idx int) error

UseTextureIdx selects texture by index for current render step

func (*Phong) UseTextureName

func (ph *Phong) UseTextureName(name string) error

UseTextureName selects texture by name for current render step

func (*Phong) UseTexturePars

func (ph *Phong) UseTexturePars(repeat mat32.Vec2, off mat32.Vec2)

UseTexturePars sets the texture parameters for the next render command: how often the texture repeats along each dimension, and the offset

type PointLight

type PointLight struct {

	// color of light a full intensity
	Color mat32.Vec3

	// position of light in world coordinates
	Pos mat32.Vec3

	// X = Linear, Y = Quad: Distance linear decay factor -- defaults to .1; Distance quadratic decay factor -- defaults to .01 -- dominates at longer distances
	Decay mat32.Vec3
	// contains filtered or unexported fields
}

PointLight is an omnidirectional light with a position and associated decay factors, which divide the light intensity as a function of linear and quadratic distance. The quadratic factor dominates at longer distances.

type PushU

type PushU struct {

	// Model Matrix: poses object in world coordinates
	ModelMtx mat32.Mat4

	// surface colors
	Color Colors

	// texture parameters
	Tex TexPars
}

PushU is the push constants structure, holding everything that updates per object -- avoids any limitations on capacity.

type Sets

type Sets int32 //enums:enum

Sets are variable set numbers - must coordinate with System sets!

const (
	MtxsSet Sets = iota
	NLightSet
	LightSet
	TexSet
)
const SetsN Sets = 4

SetsN is the highest valid value for type Sets, plus one.

func SetsValues

func SetsValues() []Sets

SetsValues returns all possible values for the type Sets.

func (Sets) Desc

func (i Sets) Desc() string

Desc returns the description of the Sets value.

func (Sets) Int64

func (i Sets) Int64() int64

Int64 returns the Sets value as an int64.

func (Sets) IsValid

func (i Sets) IsValid() bool

IsValid returns whether the value is a valid option for type Sets.

func (Sets) MarshalText

func (i Sets) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*Sets) SetInt64

func (i *Sets) SetInt64(in int64)

SetInt64 sets the Sets value from an int64.

func (*Sets) SetString

func (i *Sets) SetString(s string) error

SetString sets the Sets value from its string representation, and returns an error if the string is invalid.

func (Sets) String

func (i Sets) String() string

String returns the string representation of this Sets value.

func (*Sets) UnmarshalText

func (i *Sets) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (Sets) Values

func (i Sets) Values() []enums.Enum

Values returns all possible values for the type Sets.

type SpotLight

type SpotLight struct {

	// color of light a full intensity
	Color mat32.Vec3

	// position of light in world coordinates
	Pos mat32.Vec3

	// direction of light vector
	Dir mat32.Vec3

	// X = Angular Decay, Y = CutAngle, Z = LinDecay, W = QuadDecay: Angular decay factor -- defaults to 15; Cut off angle (in degrees) -- defaults to 45 -- max of 90; Distance linear decay factor -- defaults to 1; Distance quadratic decay factor -- defaults to 1 -- dominates at longer distances
	Decay mat32.Vec4
	// contains filtered or unexported fields
}

Spotlight is a light with a position and direction and associated decay factors and angles, which divide the light intensity as a function of linear and quadratic distance. The quadratic factor dominates at longer distances.

type TexPars

type TexPars struct {

	// how often to repeat the texture in each direction
	Repeat mat32.Vec2

	// offset for when to start the texure in each direction
	Off mat32.Vec2
}

TexPars holds texture parameters: how often to repeat the texture image and offset

func (*TexPars) Set

func (tp *TexPars) Set(rpt, off mat32.Vec2)

type Texture

type Texture struct {
	Image *image.RGBA
}

Texture has texture image -- stored as image.RGBA for GPU compatibility

func NewTexture

func NewTexture(img image.Image) *Texture

func (*Texture) Set

func (tx *Texture) Set(img image.Image)

Set sets values

Jump to

Keyboard shortcuts

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