shaman.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 renderer
  5. import (
  6. "fmt"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "github.com/g3n/engine/gls"
  11. "github.com/g3n/engine/material"
  12. "github.com/g3n/engine/renderer/shaders"
  13. )
  14. // Regular expression to parse #include <name> directive
  15. var rexInclude *regexp.Regexp
  16. func init() {
  17. rexInclude = regexp.MustCompile(`#include\s+<(.*)>`)
  18. }
  19. // ShaderSpecs describes the specification of a compiled shader program
  20. type ShaderSpecs struct {
  21. Name string // Shader name
  22. Version string // GLSL version
  23. ShaderUnique bool // indicates if shader is independent of lights and textures
  24. UseLights material.UseLights // Bitmask indicating which lights to consider
  25. AmbientLightsMax int // Current number of ambient lights
  26. DirLightsMax int // Current Number of directional lights
  27. PointLightsMax int // Current Number of point lights
  28. SpotLightsMax int // Current Number of spot lights
  29. MatTexturesMax int // Current Number of material textures
  30. }
  31. type ProgSpecs struct {
  32. program *gls.Program // program object
  33. specs ShaderSpecs // associated specs
  34. }
  35. type Shaman struct {
  36. gs *gls.GLS
  37. includes map[string]string // include files sources
  38. shadersm map[string]string // maps shader name to its template
  39. proginfo map[string]shaders.ProgramInfo // maps name of the program to ProgramInfo
  40. programs []ProgSpecs // list of compiled programs with specs
  41. specs ShaderSpecs // Current shader specs
  42. }
  43. // NewShaman creates and returns a pointer to a new shader manager
  44. func NewShaman(gs *gls.GLS) *Shaman {
  45. sm := new(Shaman)
  46. sm.Init(gs)
  47. return sm
  48. }
  49. // Init initializes the shader manager
  50. func (sm *Shaman) Init(gs *gls.GLS) {
  51. sm.gs = gs
  52. sm.includes = make(map[string]string)
  53. sm.shadersm = make(map[string]string)
  54. sm.proginfo = make(map[string]shaders.ProgramInfo)
  55. }
  56. // AddDefaultShaders adds to this shader manager all default
  57. // include chunks, shaders and programs statically registered.
  58. func (sm *Shaman) AddDefaultShaders() error {
  59. for _, name := range shaders.Includes() {
  60. sm.AddChunk(name, shaders.IncludeSource(name))
  61. }
  62. for _, name := range shaders.Shaders() {
  63. sm.AddShader(name, shaders.ShaderSource(name))
  64. }
  65. for _, name := range shaders.Programs() {
  66. sm.proginfo[name] = shaders.GetProgramInfo(name)
  67. }
  68. return nil
  69. }
  70. // AddChunk adds a shader chunk with the specified name and source code
  71. func (sm *Shaman) AddChunk(name, source string) {
  72. sm.includes[name] = source
  73. }
  74. // AddShader adds a shader program with the specified name and source code
  75. func (sm *Shaman) AddShader(name, source string) {
  76. sm.shadersm[name] = source
  77. }
  78. // AddProgram adds a program with the specified name and associated vertex
  79. // and fragment shaders names (previously registered)
  80. func (sm *Shaman) AddProgram(name, vertexName, fragName string, others ...string) {
  81. geomName := ""
  82. if len(others) > 0 {
  83. geomName = others[0]
  84. }
  85. sm.proginfo[name] = shaders.ProgramInfo{
  86. Vertex: vertexName,
  87. Fragment: fragName,
  88. Geometry: geomName,
  89. }
  90. }
  91. // SetProgram set the shader program to satisfy the specified specs.
  92. // Returns an indication if the current shader has changed and a possible error
  93. // when creating a new shader program.
  94. // Receives a copy of the specs because it changes the fields which specify the
  95. // number of lights depending on the UseLights flags.
  96. func (sm *Shaman) SetProgram(s *ShaderSpecs) (bool, error) {
  97. // Checks material use lights bit mask
  98. specs := *s
  99. if (specs.UseLights & material.UseLightAmbient) == 0 {
  100. specs.AmbientLightsMax = 0
  101. }
  102. if (specs.UseLights & material.UseLightDirectional) == 0 {
  103. specs.DirLightsMax = 0
  104. }
  105. if (specs.UseLights & material.UseLightPoint) == 0 {
  106. specs.PointLightsMax = 0
  107. }
  108. if (specs.UseLights & material.UseLightSpot) == 0 {
  109. specs.SpotLightsMax = 0
  110. }
  111. // If current shader specs are the same as the specified specs, nothing to do.
  112. if sm.specs.Compare(&specs) {
  113. return false, nil
  114. }
  115. // Search for compiled program with the specified specs
  116. for _, pinfo := range sm.programs {
  117. if pinfo.specs.Compare(&specs) {
  118. sm.gs.UseProgram(pinfo.program)
  119. sm.specs = specs
  120. return true, nil
  121. }
  122. }
  123. // Generates new program with the specified specs
  124. prog, err := sm.GenProgram(&specs)
  125. if err != nil {
  126. return false, err
  127. }
  128. log.Debug("Created new shader:%v", specs.Name)
  129. // Save specs as current specs, adds new program to the list and activates the program
  130. sm.specs = specs
  131. sm.programs = append(sm.programs, ProgSpecs{prog, specs})
  132. sm.gs.UseProgram(prog)
  133. return true, nil
  134. }
  135. // Generates shader program from the specified specs
  136. func (sm *Shaman) GenProgram(specs *ShaderSpecs) (*gls.Program, error) {
  137. // Get info for the specified shader program
  138. progInfo, ok := sm.proginfo[specs.Name]
  139. if !ok {
  140. return nil, fmt.Errorf("Program:%s not found", specs.Name)
  141. }
  142. // Sets the defines map
  143. defines := map[string]string{}
  144. defines["GLSL_VERSION"] = "330 core"
  145. defines["AMB_LIGHTS"] = strconv.FormatUint(uint64(specs.AmbientLightsMax), 10)
  146. defines["DIR_LIGHTS"] = strconv.FormatUint(uint64(specs.DirLightsMax), 10)
  147. defines["POINT_LIGHTS"] = strconv.FormatUint(uint64(specs.PointLightsMax), 10)
  148. defines["SPOT_LIGHTS"] = strconv.FormatUint(uint64(specs.SpotLightsMax), 10)
  149. defines["MAT_TEXTURES"] = strconv.FormatUint(uint64(specs.MatTexturesMax), 10)
  150. // Get vertex shader source
  151. vertexSource, ok := sm.shadersm[progInfo.Vertex]
  152. if !ok {
  153. return nil, fmt.Errorf("Vertex shader:%s not found", progInfo.Vertex)
  154. }
  155. // Preprocess vertex shader source
  156. vertexSource, err := sm.preprocess(vertexSource, defines)
  157. if err != nil {
  158. return nil, err
  159. }
  160. //fmt.Printf("vertexSource:%s\n", vertexSource)
  161. // Get fragment shader source
  162. fragSource, ok := sm.shadersm[progInfo.Fragment]
  163. if err != nil {
  164. return nil, fmt.Errorf("Fragment shader:%s not found", progInfo.Fragment)
  165. }
  166. // Preprocess fragment shader source
  167. fragSource, err = sm.preprocess(fragSource, defines)
  168. if err != nil {
  169. return nil, err
  170. }
  171. //fmt.Printf("fragSource:%s\n", fragSource)
  172. // Checks for optional geometry shader compiled template
  173. var geomSource = ""
  174. if progInfo.Geometry != "" {
  175. // Get geometry shader source
  176. geomSource, ok = sm.shadersm[progInfo.Geometry]
  177. if !ok {
  178. return nil, fmt.Errorf("Geometry shader:%s not found", progInfo.Geometry)
  179. }
  180. // Preprocess geometry shader source
  181. geomSource, err = sm.preprocess(geomSource, defines)
  182. if err != nil {
  183. return nil, err
  184. }
  185. }
  186. // Creates shader program
  187. prog := sm.gs.NewProgram()
  188. prog.AddShader(gls.VERTEX_SHADER, vertexSource, nil)
  189. prog.AddShader(gls.FRAGMENT_SHADER, fragSource, nil)
  190. if progInfo.Geometry != "" {
  191. prog.AddShader(gls.GEOMETRY_SHADER, geomSource, nil)
  192. }
  193. err = prog.Build()
  194. if err != nil {
  195. return nil, err
  196. }
  197. return prog, nil
  198. }
  199. // preprocess preprocesses the specified source prefixing it with optional defines directives
  200. // contained in "defines" parameter and replaces '#include <name>' directives
  201. // by the respective source code of include chunk of the specified name.
  202. // The included "files" are also processed recursively.
  203. func (sm *Shaman) preprocess(source string, defines map[string]string) (string, error) {
  204. // If defines map supplied, generates prefix with glsl version directive first,
  205. // followed by "#define directives"
  206. var prefix = ""
  207. if defines != nil {
  208. prefix = fmt.Sprintf("#version %s\n", defines["GLSL_VERSION"])
  209. for name, value := range defines {
  210. if name == "GLSL_VERSION" {
  211. continue
  212. }
  213. prefix = prefix + fmt.Sprintf("#define %s %s\n", name, value)
  214. }
  215. }
  216. // Find all string submatches for the "#include <name>" directive
  217. matches := rexInclude.FindAllStringSubmatch(source, 100)
  218. if len(matches) == 0 {
  219. return prefix + source, nil
  220. }
  221. // For each directive found, replace the name by the respective include chunk source code
  222. var newSource = source
  223. for _, m := range matches {
  224. // Get the source of the include chunk with the match <name>
  225. incSource := sm.includes[m[1]]
  226. if len(incSource) == 0 {
  227. return "", fmt.Errorf("Include:[%s] not found", m[1])
  228. }
  229. // Preprocess the include chunk source code
  230. incSource, err := sm.preprocess(incSource, nil)
  231. if err != nil {
  232. return "", err
  233. }
  234. // Replace all occurrences of the include directive with its processed source code
  235. newSource = strings.Replace(newSource, m[0], incSource, -1)
  236. }
  237. return prefix + newSource, nil
  238. }
  239. // Compare compares two shaders specifications structures
  240. func (ss *ShaderSpecs) Compare(other *ShaderSpecs) bool {
  241. if ss.Name != other.Name {
  242. return false
  243. }
  244. if other.ShaderUnique {
  245. return true
  246. }
  247. if ss.AmbientLightsMax == other.AmbientLightsMax &&
  248. ss.DirLightsMax == other.DirLightsMax &&
  249. ss.PointLightsMax == other.PointLightsMax &&
  250. ss.SpotLightsMax == other.SpotLightsMax &&
  251. ss.MatTexturesMax == other.MatTexturesMax {
  252. return true
  253. }
  254. return false
  255. }