shaman.go 9.0 KB

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