forked from fogleman/fauxgl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshader.go
89 lines (75 loc) · 2.07 KB
/
shader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package fauxgl
import "math"
type Shader interface {
Vertex(Vertex) Vertex
Fragment(Vertex) Color
}
type DefaultShader struct {
Matrix Matrix
Light Vector
Camera Vector
Color Color
Texture Texture
}
func NewDefaultShader(matrix Matrix, light, camera Vector, color Color) *DefaultShader {
return &DefaultShader{matrix, light, camera, color, nil}
}
func (shader *DefaultShader) Vertex(v Vertex) Vertex {
v.Output = shader.Matrix.MulPositionW(v.Position)
return v
}
func (shader *DefaultShader) Fragment(v Vertex) Color {
color := shader.Color
if color == Discard {
color = v.Color
}
if shader.Texture != nil {
color = shader.Texture.BilinearSample(v.Texture.X, v.Texture.Y)
}
diffuse := math.Max(v.Normal.Dot(shader.Light), 0)
specular := 0.0
if diffuse > 0 {
camera := shader.Camera.Sub(v.Position).Normalize()
specular = math.Max(camera.Dot(shader.Light.Negate().Reflect(v.Normal)), 0)
specular = math.Pow(specular, 50)
}
light := Clamp(diffuse+specular, 0.1, 1)
return color.MulScalar(light).Alpha(color.A)
}
type SolidColorShader struct {
Matrix Matrix
Color Color
}
func NewSolidColorShader(matrix Matrix, color Color) *SolidColorShader {
return &SolidColorShader{matrix, color}
}
func (shader *SolidColorShader) Vertex(v Vertex) Vertex {
v.Output = shader.Matrix.MulPositionW(v.Position)
return v
}
func (shader *SolidColorShader) Fragment(v Vertex) Color {
return shader.Color
}
type DiffuseShader struct {
Matrix Matrix
LightDir Vector
Color Color
Ambient Color
Diffuse Color
}
func NewDiffuseShader(matrix Matrix, light Vector, color, ambient, diffuse Color) *DiffuseShader {
return &DiffuseShader{matrix, light, color, ambient, diffuse}
}
func (shader *DiffuseShader) Vertex(v Vertex) Vertex {
v.Output = shader.Matrix.MulPositionW(v.Position)
return v
}
func (shader *DiffuseShader) Fragment(v Vertex) Color {
color := shader.Color
if color == Discard {
color = v.Color
}
diffuse := math.Max(v.Normal.Dot(shader.LightDir), 0)
light := shader.Ambient.Add(shader.Diffuse.MulScalar(diffuse))
return color.Mul(light).Alpha(color.A)
}