shader.go (1961B)
1 // Copyright 2020 The Ebiten Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package opengl 16 17 import ( 18 "fmt" 19 20 "github.com/hajimehoshi/ebiten/v2/internal/driver" 21 "github.com/hajimehoshi/ebiten/v2/internal/shaderir" 22 "github.com/hajimehoshi/ebiten/v2/internal/shaderir/glsl" 23 ) 24 25 type Shader struct { 26 id driver.ShaderID 27 graphics *Graphics 28 29 ir *shaderir.Program 30 p program 31 } 32 33 func newShader(id driver.ShaderID, graphics *Graphics, program *shaderir.Program) (*Shader, error) { 34 s := &Shader{ 35 id: id, 36 graphics: graphics, 37 ir: program, 38 } 39 if err := s.compile(); err != nil { 40 return nil, err 41 } 42 return s, nil 43 } 44 45 func (s *Shader) ID() driver.ShaderID { 46 return s.id 47 } 48 49 func (s *Shader) Dispose() { 50 s.graphics.context.deleteProgram(s.p) 51 s.graphics.removeShader(s) 52 } 53 54 func (s *Shader) compile() error { 55 vssrc, fssrc := glsl.Compile(s.ir) 56 57 vs, err := s.graphics.context.newShader(vertexShader, vssrc) 58 if err != nil { 59 return fmt.Errorf("opengl: vertex shader compile error: %v, source:\n%s", err, vssrc) 60 } 61 defer s.graphics.context.deleteShader(vs) 62 63 fs, err := s.graphics.context.newShader(fragmentShader, fssrc) 64 if err != nil { 65 return fmt.Errorf("opengl: fragment shader compile error: %v, source:\n%s", err, fssrc) 66 } 67 defer s.graphics.context.deleteShader(fs) 68 69 p, err := s.graphics.context.newProgram([]shader{vs, fs}, theArrayBufferLayout.names()) 70 if err != nil { 71 return err 72 } 73 74 s.p = p 75 return nil 76 }