program.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gls
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "github.com/g3n/engine/math32"
  10. "io"
  11. "strconv"
  12. "strings"
  13. )
  14. // Shader Program Object
  15. type Program struct {
  16. // Shows source code in error messages
  17. ShowSource bool
  18. gs *GLS
  19. handle uint32
  20. shaders []shaderInfo
  21. uniforms map[string]int32
  22. Specs interface{}
  23. }
  24. type shaderInfo struct {
  25. stype uint32
  26. source string
  27. defines map[string]interface{}
  28. handle uint32
  29. }
  30. // Map shader types to names
  31. var shaderNames = map[uint32]string{
  32. VERTEX_SHADER: "Vertex Shader",
  33. FRAGMENT_SHADER: "Fragment Shader",
  34. }
  35. // NewProgram creates a new empty shader program object.
  36. // Use this type methods to add shaders and build the final program.
  37. func (gs *GLS) NewProgram() *Program {
  38. prog := new(Program)
  39. prog.gs = gs
  40. prog.shaders = make([]shaderInfo, 0)
  41. prog.uniforms = make(map[string]int32)
  42. prog.ShowSource = true
  43. return prog
  44. }
  45. // AddShaders adds a shader to this program.
  46. // This must be done before the program is built.
  47. func (prog *Program) AddShader(stype uint32, source string, defines map[string]interface{}) {
  48. if prog.handle != 0 {
  49. log.Fatal("Program already built")
  50. }
  51. prog.shaders = append(prog.shaders, shaderInfo{stype, source, defines, 0})
  52. }
  53. // Build builds the program compiling and linking the previously supplied shaders.
  54. func (prog *Program) Build() error {
  55. if prog.handle != 0 {
  56. return fmt.Errorf("Program already built")
  57. }
  58. // Checks if shaders were provided
  59. if len(prog.shaders) == 0 {
  60. return fmt.Errorf("No shaders supplied")
  61. }
  62. // Create program
  63. prog.handle = prog.gs.CreateProgram()
  64. if prog.handle == 0 {
  65. return fmt.Errorf("Error creating program")
  66. }
  67. // Clean unused GL allocated resources
  68. defer func() {
  69. for _, sinfo := range prog.shaders {
  70. if sinfo.handle != 0 {
  71. prog.gs.DeleteShader(sinfo.handle)
  72. sinfo.handle = 0
  73. }
  74. }
  75. }()
  76. // Compiles and attach each shader
  77. for _, sinfo := range prog.shaders {
  78. // Creates string with defines from specified parameters
  79. deflines := make([]string, 0)
  80. if sinfo.defines != nil {
  81. for pname, pval := range sinfo.defines {
  82. line := "#define " + pname + " "
  83. switch val := pval.(type) {
  84. case bool:
  85. if val {
  86. deflines = append(deflines, line)
  87. }
  88. case float32:
  89. line += strconv.FormatFloat(float64(val), 'f', -1, 32)
  90. deflines = append(deflines, line)
  91. default:
  92. panic("Parameter type not supported")
  93. }
  94. }
  95. }
  96. deftext := strings.Join(deflines, "\n")
  97. // Compile shader
  98. shader, err := prog.CompileShader(sinfo.stype, sinfo.source+deftext)
  99. if err != nil {
  100. prog.gs.DeleteProgram(prog.handle)
  101. prog.handle = 0
  102. msg := fmt.Sprintf("Error compiling %s: %s", shaderNames[sinfo.stype], err)
  103. if prog.ShowSource {
  104. source := FormatSource(sinfo.source + deftext)
  105. msg += source
  106. }
  107. return errors.New(msg)
  108. }
  109. sinfo.handle = shader
  110. prog.gs.AttachShader(prog.handle, shader)
  111. }
  112. // Link program and checks for errors
  113. prog.gs.LinkProgram(prog.handle)
  114. var status int32
  115. prog.gs.GetProgramiv(prog.handle, LINK_STATUS, &status)
  116. if status == FALSE {
  117. log := prog.gs.GetProgramInfoLog(prog.handle)
  118. prog.handle = 0
  119. return fmt.Errorf("Error linking program: %v", log)
  120. }
  121. return nil
  122. }
  123. // Handle returns the handle of this program
  124. func (prog *Program) Handle() uint32 {
  125. return prog.handle
  126. }
  127. // GetAttributeLocation returns the location of the specified attribute
  128. // in this program. This location is internally cached.
  129. func (prog *Program) GetAttribLocation(name string) int32 {
  130. return prog.gs.GetAttribLocation(prog.handle, name)
  131. }
  132. // GetUniformLocation returns the location of the specified uniform in this program.
  133. // This location is internally cached.
  134. func (prog *Program) GetUniformLocation(name string) int32 {
  135. // Try to get from the cache
  136. loc, ok := prog.uniforms[name]
  137. if ok {
  138. prog.gs.stats.UnilocHits++
  139. return loc
  140. }
  141. // Get location from GL
  142. loc = prog.gs.GetUniformLocation(prog.handle, name)
  143. // Cache result
  144. prog.uniforms[name] = loc
  145. if loc < 0 {
  146. log.Warn("GetUniformLocation(%s) NOT FOUND", name)
  147. }
  148. prog.gs.stats.UnilocMiss++
  149. return loc
  150. }
  151. // SetUniformInt sets this program uniform variable specified by
  152. // its location to the the value of the specified int
  153. func (prog *Program) SetUniformInt(loc int32, v int) {
  154. prog.gs.Uniform1i(loc, int32(v))
  155. }
  156. // SetUniformFloat sets this program uniform variable specified by
  157. // its location to the the value of the specified float
  158. func (prog *Program) SetUniformFloat(loc int32, v float32) {
  159. prog.gs.Uniform1f(loc, v)
  160. }
  161. // SetUniformVector2 sets this program uniform variable specified by
  162. // its location to the the value of the specified Vector2
  163. func (prog *Program) SetUniformVector2(loc int32, v *math32.Vector2) {
  164. prog.gs.Uniform2f(loc, v.X, v.Y)
  165. }
  166. // SetUniformVector3 sets this program uniform variable specified by
  167. // its location to the the value of the specified Vector3
  168. func (prog *Program) SetUniformVector3(loc int32, v *math32.Vector3) {
  169. prog.gs.Uniform3f(loc, v.X, v.Y, v.Z)
  170. }
  171. // SetUniformVector4 sets this program uniform variable specified by
  172. // its location to the the value of the specified Vector4
  173. func (prog *Program) SetUniformVector4(loc int32, v *math32.Vector4) {
  174. prog.gs.Uniform4f(loc, v.X, v.Y, v.Z, v.W)
  175. }
  176. // SetUniformMatrix3 sets this program uniform variable specified by
  177. // its location with the values from the specified Matrix3.
  178. func (prog *Program) SetUniformMatrix3(loc int32, m *math32.Matrix3) {
  179. prog.gs.UniformMatrix3fv(loc, 1, false, &m[0])
  180. }
  181. // SetUniformMatrix4 sets this program uniform variable specified by
  182. // its location with the values from the specified Matrix4.
  183. func (prog *Program) SetUniformMatrix4(loc int32, m *math32.Matrix4) {
  184. prog.gs.UniformMatrix4fv(loc, 1, false, &m[0])
  185. }
  186. // SetUniformIntByName sets this program uniform variable specified by
  187. // its name to the value of the specified int.
  188. // The specified name location is cached internally.
  189. func (prog *Program) SetUniformIntByName(name string, v int) {
  190. prog.gs.Uniform1i(prog.GetUniformLocation(name), int32(v))
  191. }
  192. // SetUniformFloatByName sets this program uniform variable specified by
  193. // its name to the value of the specified float32.
  194. // The specified name location is cached internally.
  195. func (prog *Program) SetUniformFloatByName(name string, v float32) {
  196. prog.gs.Uniform1f(prog.GetUniformLocation(name), v)
  197. }
  198. // SetUniformVector2ByName sets this program uniform variable specified by
  199. // its name to the values from the specified Vector2.
  200. // The specified name location is cached internally.
  201. func (prog *Program) SetUniformVector2ByName(name string, v *math32.Vector2) {
  202. prog.gs.Uniform2f(prog.GetUniformLocation(name), v.X, v.Y)
  203. }
  204. // SetUniformVector3ByName sets this program uniform variable specified by
  205. // its name to the values from the specified Vector3.
  206. // The specified name location is cached internally.
  207. func (prog *Program) SetUniformVector3ByName(name string, v *math32.Vector3) {
  208. prog.gs.Uniform3f(prog.GetUniformLocation(name), v.X, v.Y, v.Z)
  209. }
  210. // SetUniformVector4ByName sets this program uniform variable specified by
  211. // its name to the values from the specified Vector4.
  212. // The specified name location is cached internally.
  213. func (prog *Program) SetUniformVector4ByName(name string, v *math32.Vector4) {
  214. prog.gs.Uniform4f(prog.GetUniformLocation(name), v.X, v.Y, v.Z, v.W)
  215. }
  216. // SetUniformMatrix3ByName sets this program uniform variable specified by
  217. // its name with the values from the specified Matrix3.
  218. // The specified name location is cached internally.
  219. func (prog *Program) SetUniformMatrix3ByName(name string, m *math32.Matrix3) {
  220. prog.gs.UniformMatrix3fv(prog.GetUniformLocation(name), 1, false, &m[0])
  221. }
  222. // SetUniformMatrix4ByName sets this program uniform variable specified by
  223. // its name with the values from the specified Matrix4.
  224. // The location of the name is cached internally.
  225. func (prog *Program) SetUniformMatrix4ByName(name string, m *math32.Matrix4) {
  226. prog.gs.UniformMatrix4fv(prog.GetUniformLocation(name), 1, false, &m[0])
  227. }
  228. // SetUniformColorByName set this program uniform variable specified by
  229. // its name to the values from the specified Color
  230. // The specified name location is cached internally.
  231. func (prog *Program) SetUniformColorByName(name string, c *math32.Color) {
  232. prog.gs.Uniform3f(prog.GetUniformLocation(name), c.R, c.G, c.B)
  233. }
  234. // SetUniformColor4ByName set this program uniform variable specified by
  235. // its name to the values from the specified Color4
  236. // The specified name location is cached internally.
  237. func (prog *Program) SetUniformColor4ByName(name string, c *math32.Color4) {
  238. prog.gs.Uniform4f(prog.GetUniformLocation(name), c.R, c.G, c.B, c.A)
  239. }
  240. // CompileShader creates and compiles a shader of the specified type and with
  241. // the specified source code and returns a non-zero value by which
  242. // it can be referenced.
  243. func (prog *Program) CompileShader(stype uint32, source string) (uint32, error) {
  244. // Creates shader object
  245. shader := prog.gs.CreateShader(stype)
  246. if shader == 0 {
  247. return 0, fmt.Errorf("Error creating shader")
  248. }
  249. // Set shader source and compile it
  250. prog.gs.ShaderSource(shader, source)
  251. prog.gs.CompileShader(shader)
  252. // Get the shader compiler log
  253. slog := prog.gs.GetShaderInfoLog(shader)
  254. // Get the shader compile status
  255. var status int32
  256. prog.gs.GetShaderiv(shader, COMPILE_STATUS, &status)
  257. if status == FALSE {
  258. return shader, fmt.Errorf("%s", slog)
  259. }
  260. // If the shader compiled OK but the log has data,
  261. // logs this data instead of returning error
  262. if len(slog) > 2 {
  263. log.Warn("%s", slog)
  264. }
  265. return shader, nil
  266. }
  267. // FormatSource returns the supplied program source code with
  268. // line numbers prepended.
  269. func FormatSource(source string) string {
  270. // Reads all lines from the source string
  271. lines := make([]string, 0)
  272. buf := bytes.NewBuffer([]byte(source))
  273. for {
  274. line, err := buf.ReadBytes('\n')
  275. if err != nil {
  276. if err == io.EOF {
  277. break
  278. }
  279. panic(err)
  280. }
  281. lines = append(lines, string(line[:len(line)-1]))
  282. }
  283. // Adds a final line terminator
  284. lines = append(lines, "\n")
  285. // Prepends the line number for each line
  286. ndigits := len(strconv.Itoa(len(lines)))
  287. format := "%0" + strconv.Itoa(ndigits) + "d:%s"
  288. formatted := make([]string, 0)
  289. for pos, l := range lines {
  290. fline := fmt.Sprintf(format, pos+1, l)
  291. formatted = append(formatted, fline)
  292. }
  293. return strings.Join(formatted, "\n")
  294. }