diff --git a/examples/shader/main.go b/examples/shader/main.go index 00ad3625d..15b5003b1 100644 --- a/examples/shader/main.go +++ b/examples/shader/main.go @@ -29,17 +29,20 @@ const ( const shaderSrc = `package main +// Internal_ViewportSize is a predefined uniform variable. +// TODO: Hide this and create a function for the projection matrix? + func Vertex(position vec2, texCoord vec2, color vec4) vec4 { return mat4( - 2.0/640, 0, 0, 0, - 0, 2.0/480, 0, 0, + 2.0/Internal_ViewportSize.x, 0, 0, 0, + 0, 2.0/Internal_ViewportSize.y, 0, 0, 0, 0, 1, 0, -1, -1, 0, 1, ) * vec4(position, 0, 1) } func Fragment(position vec4) vec4 { - return vec4(position.x/640, position.y/480, 0, 1) + return vec4(position.x/Internal_ViewportSize.x, position.y/Internal_ViewportSize.y, 0, 1) }` type Game struct { diff --git a/image.go b/image.go index 4a359a10f..2ff60589c 100644 --- a/image.go +++ b/image.go @@ -384,6 +384,10 @@ func (i *Image) DrawTrianglesWithShader(vertices []Vertex, indices []uint16, sha } } + // The last uniform variable is Internal_ViewportSize. + // The actual value is set at graphicscommand package. + us = append(us, []float32{0, 0}) + var bx0, by0, bx1, by1 float32 if firstImage != nil { b := firstImage.Bounds() diff --git a/internal/graphicscommand/command.go b/internal/graphicscommand/command.go index 60c834193..6bba313d2 100644 --- a/internal/graphicscommand/command.go +++ b/internal/graphicscommand/command.go @@ -453,6 +453,13 @@ func (c *drawTrianglesCommand) Exec(indexOffset int) error { us[i] = v } } + + // The last uniform variables are added at /shader.go and represents a viewport size. + w, h := c.dst.InternalSize() + viewport := us[len(us)-1].([]float32) + viewport[0] = float32(w) + viewport[1] = float32(h) + return theGraphicsDriver.DrawShader(c.dst.image.ID(), c.shader.shader.ID(), c.nindices, indexOffset, c.mode, us) } return theGraphicsDriver.Draw(c.dst.image.ID(), c.src.image.ID(), c.nindices, indexOffset, c.mode, c.color, c.filter, c.address) diff --git a/shader.go b/shader.go index d9d1fa724..cacd631d7 100644 --- a/shader.go +++ b/shader.go @@ -15,16 +15,25 @@ package ebiten import ( + "bytes" + "github.com/hajimehoshi/ebiten/internal/buffered" "github.com/hajimehoshi/ebiten/internal/shader" ) +const shaderSuffix = ` +var Internal_ViewportSize vec2` + type Shader struct { shader *buffered.Shader } func NewShader(src []byte) (*Shader, error) { - s, err := shader.Compile(src, "Vertex", "Fragment") + var b bytes.Buffer + b.Write(src) + b.Write([]byte(shaderSuffix)) + + s, err := shader.Compile(b.Bytes(), "Vertex", "Fragment") if err != nil { return nil, err }